Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How I create a cookie in Django to keep a view of a list using vanilla Javascript?
I have a Django view, where the user can choose between 2 different "views" of a list through a toggle button. The map view where a map is displayed with markers and some information and a list view where a list is displayed with the same information but with a list view. When the user clicks the toggle button between one or another option, there is no problem, because I implemented an onClick Javascript function where I change the style display, and that works perfect, the problem is when the user reloads the page. supposes that I put by default the map view, but the user change to the list view by clicking the toggle button, now if he/she reload the page, the view will have to be the list view, I know that I can accomplish this using a cookie but I don't know how to implement the update of the cookie every time the user clicks one of the toggle buttons with vanilla Javascript or in my python view. I know that one solution may be creating 2 Django views one "mapView" and another "listView" so when you click the buttons take to another URL, but I want … -
TypeError at /check-out getting dict value but i want both dict and also specified value
When i checkout an order i got this error.I am passing a dict in customer object but whenever i remove dict function i cant login anymore. i cant also fetch customer details. Here is my views.py(i think my problems are in these views only): class Login(View): def get(self, request): return render(request, 'signupsignin/signin.html') def post(self, request): phone_number = request.POST.get('phone_number') password = request.POST.get('password') customer = Customer.get_customer(phone_number) error_message = None if customer: match = check_password(password, customer.password) if match: customer.__dict__.pop('_state') request.session['customer'] = customer.__dict__ #request.session['csutomer'] = customer.id return redirect('Home') else: error_message = 'Phone number or Password didnt match on our record' else: error_message = 'No Customer Found! Please Registrer First!' print(phone_number, password) context = {'error_message': error_message} return render(request, 'signupsignin/signin.html', context) class Checkout(View): def post(self, request): fname = request.POST.get('fname') phone = request.POST.get('phone') address = request.POST.get('address') cart = request.session.get('cart') customer = request.session.get('customer') products = Product.get_products_id(list(cart.keys())) print(fname, phone, address, products, cart, customer) for product in products: order = Order(customer=Customer(id=customer), product=product, fname=fname, price=product.price, phone=phone, address=address, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect('cart') Here is my urls.py for these function: path('login', Login.as_view(), name='login'), path('check-out', Checkout.as_view(), name="check-out"), I am getting this error: TypeError at /check-out Field 'id' expected a number but got {'id': 3, 'phone_number': '01622153196', 'email': 'sakibovi@gmail.com', 'password': 'pbkdf2_sha256$216000$H2o5Do81kxI0$2tmMwSnSJHBVBTU9tQ8/tkN7h1ZQpRKrTAKkax1xp2Y=', 'coin': … -
change the serialized data
I know question title is not clear and sorry for that. my question is how can I change the way response looks right now # serializers.py class UserCommentSerializer(serializers.ModelSerializer): slug = serializers.SerializerMethodField(read_only=True) class Meta: model = Comment fields = '__all__' def get_slug(self, obj): id = obj.object_id return BlogPost.objects.values('slug').get(id=id) The response looks something like this "results": [ { "id": 49, "slug": { "slug": "ghfj-jkbkj-kjkjk" }, }] I want it to look "results": [ { "id": 49, "slug": "ghfj-jkbkj-kjkjk" }, }] See, if you can help -
when creating a user in Django Admin it does not hash the password?
I am trying to Create a user from my Django Admin (the project is a rest api) using the Django REST framework. admin.py class UserFrame(UserAdmin): list_display = ["name", "email", "date_of_creation", "is_active"] list_editable = ["is_active"] admin.site.register(models.AccountProfile, UserFrame) The error I am getting : Unknown field(s) (date_joined, last_name, first_name) specified for AccountProfile AccountProfile is my custom user model which inherits from AbstractBaseUser and has a BaseUserManager. please help! thank you! -
Testing Django project from outside, is it good approach?
We have a big monolithic Django project (A) with a lot of RESTFUL API endpoints. We're planning to move some of its features into smaller service (B). Before doing that we're going to write tests for these endpoints. We want to a separate testing project that will capable of testing project A and B. When I do an Internet search there are not many resources about that approach. Does anyone try something like this? -
nginx webserver with zscaler as reverse proxy
I have a website running on Django with Nginx as a webserver and Redhat8 OS. The site works fine until now. Now we are trying to put a reverse proxy in front of our Nginx web server. But my authentication fails with an error message. Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. What I understand is, when the request is passed through the reverse proxy the CSRF cookies are not set properly. But the same URL has a cookie when accessed without a reverse proxy. Below is my nginx.config file for your reference. upstream app_server { server unix:/run/gunicorn.sock fail_timeout=0; } server { listen 443 ssl default_server; ssl on; ssl_certificate /etc/httpd/ssl/portal_com.pem; ssl_certificate_key /etc/httpd/ssl/portal_com.key; server_name portal.company.com; # <- insert here the ip address/domain name ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3; keepalive_timeout 5; client_max_body_size 4G; access_log /home/Project/logs/nginx-access.log; error_log /home/Project/logs/nginx-error.log; proxy_connect_timeout 20; proxy_send_timeout 20; proxy_read_timeout 20; send_timeout 20; client_body_timeout 20; location … -
Bulk create on related models using csv
I'm trying to use bulk_create in order to add objects to related models. Here i'm fetching the csv file through post request which contains required fields. As of now I can add items to models which is unrelated using the csv file and bulk_create and it's working. class BulkAPI(APIView): def post(self, request): paramFile = io.TextIOWrapper(request.FILES['requirementfile'].file) dict1 = csv.DictReader(paramFile) list_of_dict = list(dict1) objs = [ ManpowerRequirement( project=row['project'], position=row['position'], quantity=row['quantity'], project_location=row['project_location'], requested_date=row['requested_date'], required_date=row['required_date'], employment_type=row['employment_type'], duration=row['duration'], visa_type=row['visa_type'], remarks=row['remarks'], ) for row in list_of_dict ] try: msg = ManpowerRequirement.objects.bulk_create(objs) returnmsg = {"status_code": 200} print('imported successfully') except Exception as e: print('Error While Importing Data: ', e) returnmsg = {"status_code": 500} return JsonResponse(returnmsg) My models are: class ManpowerRequirement(models.Model): project = models.CharField(max_length=60) position = models.CharField(max_length=60) quantity = models.IntegerField() project_location = models.CharField(max_length=60) requested_date = models.DateField() required_date = models.DateField() employment_type = models.CharField(max_length=60,choices = EMPLOYMENT_TYPE_CHOICES, default = 'Permanent') duration = models.CharField(max_length=60) visa_type = models.CharField(max_length=60) remarks = models.TextField(blank = True , null=True) def __str__(self): return self.project class Meta: verbose_name_plural = "Manpower_Requirement" class Fulfillment(models.Model): candidate_name = models.CharField(max_length=60) manpower_requirement = models.ForeignKey(ManpowerRequirement, on_delete=models.CASCADE) passport_number = models.CharField(blank = True, max_length=60) subcontract_vendors = models.CharField(max_length=200,blank = True , null=True ,default='') joined_date = models.DateField(blank = True, null = True, default = '') remarks = models.TextField( blank = True,null … -
Django Server not running on Wifi
Django Server not running on Wifi I am having trouble in running Django Server on my Wifi so that other devices can see my project. My IPv4 Address : 192.168.10.84 My Allowed Hosts Looks like this - ALLOWED HOSTS = ['192.168.10.84', '127.0.0.1'] when I run the below command, python manage.py runserver 0.0.0.0:8000 and I check from other device by going to the address http://192.168.10.84:8000, it shows THIS SITE CAN'T BE REACHED ANy idea why it's not working?? -
Django compared to Microservices
I've been learning what microservices are and heard something like this: when you use microservices, if one part of your system fails (say the card processing part of an online store platform), you can still use others (like browsing products in the store). However, I have experience with Django and I know that if you mess up a function for card processing, you CAN still use the rest of the platform, it will just fail when you use that function. So, is Django then automatically microservices? Thanks! -
How do I target the Django setting module in an environmental variable on PythonAnywhere?
I want to run my stand-alone script csvImp.py, which interacts with the database used by my Django site BilliClub. I'm running the script from the project root (~/BilliClub) on my virtual environment django2. I've followed the instructions here but for DJANGO_SETTINGS_MODULE rather than the secret key. The part that trips me up is what value to assign to the environmental variable. Every iteration I've tried has yielded an error like ModuleNotFoundError: No module named 'BilliClub' after running (django2) 04:02 ~/BilliClub $ python ./pigs/csvImp.py. I am reloading the shell every time I try to change the variable in .env so the postactivate script runs each time and I'm making sure to re-enter my virtualenv. The problem just seems to be my inability to figure out how to path to the settings module. The .env file: # /home/username/BilliClub/.env # DJANGO_SETTINGS_MODULE="[what goes here???]" Full path of my settings.py is /home/username/BilliClub/BilliClub/settings.py. Abridged results from running tree: (django2) 04:33 ~ $ tree . ├── BilliClub │ ├── BilliClub │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ ├── media │ ├── pigs │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py … -
Other user's profile is not showing, It is showing only current user name . How to display other user's profile?
I am creating a web app and I want this to display other user's profile through the user's post. I mean when a user click on other user's profile for see the other user's information then it will show the other user's profile. I've tried everything but it is showing the name of the current user information after click on the post. Please Help me in this. Thank you very Much. I will really apppreciate your Help. Here is my Code:- views.py def post_profile(request,username): poste = Profile.objects.get(user=request.user) context = {'poste':poste} return render(request, 'mains/post_profile.html', context) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') date_added = models.DateTimeField(auto_now_add=True) post_profile.html - ( This is the template of, which will show the other user's profile . ) {% extends "mains/base.html" %} {% block content %} {% for topic in current_user %} <a>{{ topic.username }}</a><br> {% empty %} <li>No informtion.</li> {% endfor %} </ul> {% endblock content %} Please help me in this, I don't know where is the problem -
Django Rest Framework: foreign key field is required in viewset or serializer
I am very new to Django Rest Framework (DRF). I have read that viewsets are very good, because it reduces the amount of code, but I found it more complex. Description: Imagine that I want to implement a phonebook API, in which we have some users and each of them has it own contacts and each contact can have several phone number. So, I have three models here. User (Default Django model) Contact class Contact(models.Model): owner = models.ForeignKey( User, on_delete=models.CASCADE, related_name='contacts' ) name = models.CharField( max_length=70 ) description = models.TextField() Phone Number class Phones(models.Model): person = models.ForeignKey( Contact, related_name="phones", on_delete=models.CASCADE, ) phone_no = models.CharField( max_length=11, ) Problem Definition What I want is to create new contact with the current request.user. So I should have my contact.serializers like the following: class ContactSerializer(serializers.ModelSerializer): owner = serializers.PrimaryKeyRelatedField( queryset=User.objects.all(), ) class Meta: model = Contact fields = ['id', 'owner', 'name', 'description'] read_only_fields = ['owner'] and my views is like: class ContactViewSet(viewsets.ModelViewSet): queryset = Contact.objects.all() serializer_class = ContactSerializer permission_classes = [IsCreator] def get_permissions(self): if self.request.method == "GET": self.permission_classes = [IsCreator, permissions.IsAdminUser,] if self.request.method == "POST": self.permission_classes = [permissions.IsAuthenticated,] if self.request.method == "PUT": self.permission_classes = [IsCreator] if self.request.method == "DELETE": self.permission_classes = [] return super(ContactViewSet, self).get_permissions() … -
error with migration when i deploy my project
i have troble when migrate my module by django on cpanel i use phpPgAdmin 5.6 django 2.2.6 i got following error when migrare but when i use migrate fake , the error disapear but the site can't be lunch this is following error Running migrations: Applying authtoken.0002_auto_20160226_1747...Traceback (most recent call last): File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.SyntaxError: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... -
Django, Why is only the'view' permission authenticated, and the rest of the permissions are not? (DjangoModelPermissions)
First of all, I can't speak English well. test1 account permissions.py (DjangoModelPermissions) class CustomPermissions(permissions.BasePermission): perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': [], 'HEAD': [], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } authenticated_users_only = True def get_required_permissions(self, method, model_cls): kwargs = { 'app_label': model_cls._meta.app_label, 'model_name': model_cls._meta.model_name } if method not in self.perms_map: raise exceptions.MethodNotAllowed(method) return [perm % kwargs for perm in self.perms_map[method]] def _queryset(self, view): assert hasattr(view, 'get_queryset') \ or getattr(view, 'queryset', None) is not None, ( 'Cannot apply {} on a view that does not set ' '`.queryset` or have a `.get_queryset()` method.' ).format(self.__class__.__name__) if hasattr(view, 'get_queryset'): queryset = view.get_queryset() assert queryset is not None, ( '{}.get_queryset() returned None'.format(view.__class__.__name__) ) return queryset return view.queryset def has_permission(self, request, view): if getattr(view, '_ignore_model_permissions', False): return True if not request.user or ( not request.user.is_authenticated and self.authenticated_users_only): return False queryset = self._queryset(view) perms = self.get_required_permissions(request.method, queryset.model) return request.user.has_perms(perms) view.py from rest_framework import viewsets, permissions, generics from .serializers import PlayerListSerializer from .models import PlayerList from .permission import CustomPermissions class ListPlayer(generics.ListCreateAPIView): permission_classes = [CustomPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class AddListPlayer(generics.ListCreateAPIView): permission_classes = [CustomPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class DetailPlayer(generics.RetrieveUpdateDestroyAPIView): permission_classes = [CustomPermissions, ] queryset = PlayerList.objects.all() serializer_class = PlayerListSerializer … -
How can i convert from IntgerField(Timestamp) to python datetime
unban_date = models.IntegerField() This Output = All the timestamps from the database I need it to convert to DateTime I came up with this but it does not work as it does not take IntegarField intToParser = datetime.datetime.fromtimestamp(unban_date) parserToDate = intToParser.strftime('%Y-%b-%d %H:%M:%S') print(parserToDate) This is dJango Models -
How to implement models for Branch wise permission management in DJango?
I was trying to implement CRM application in Django. The company will have multiple branches, and staff also work for one more branches in different roles. For example, they may work in branch-A as a sales manager and branch -b as a Branch Manager, I was trying to implement that by Django Group and Permission, But that is not efficient way, it will be very help full if somebody help me to do this.Please see my code from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ from branch.models import Branch from django.contrib.auth.models import Group from django.contrib.auth.models import Permission class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) … -
How to pass multiple instances to Django forms
I have a user profile which contains data about the user's education details as a table.The user need to edit his educational details by using a form.I need to edit the multiple education objects from the db. How can i do this ? I'm a beginner in django. Please help views.py// @method_decorator(login_required, name='dispatch') class EditTutorEducation(TemplateView): template_name = 'account/edit-education.html' def get_context_data(self, **kwargs): context = super(EditTutorEducation, self).get_context_data(**kwargs) education_object = Education.objects.filter(user = self.request.user) context['form'] = EducationEditForm(instance=education_object) ---// need help here return context def post(self, request, *args, **kwargs): education_object = Education.objects.filter(user = self.request.user) form = EducationEditForm(request.POST, instance=education_object) if form.is_valid(): form.save() else: print(form.errors) if form.errors: return TemplateResponse(request, self.template_name, {'form': form}) return redirect('/profile/') edit-education.html// <form method="post" action="." enctype="multipart/form-data"> {% csrf_token %} <table class=""> {{form}} </table> <div class="profile-btn mt-5 row justify-content-center"> <button class="btn btn-block btn-outline-primary white-hover my-3 my-sm-0" type="submit">Submit</button> </div> </form> forms.py// class EducationEditForm(forms.ModelForm): class Meta: model = Education fields = ['course','university','year'] -
Django 'Unable to configure handler 'logfile' error
I faced some errors while running the Django project. This project is using the default configurations. I checked the setting object but it was normal {'version': 1, 'disable_existing_loggers': false, 'formatters': {'standard': {'format': '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s', 'datefmt': '%Y-%m-%d %I:%M:%S %p US/Central'}}, 'handlers': {'console': {'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'standard'}, 'logfile': {'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/var/log/django.log', 'maxBytes': 1000000, 'backupCount': 10, 'formatter': 'standard'}}, 'loggers': {'django': {'handlers': ['console', 'logfile'], 'propagate': true}}} Please help me with this issue. Thank you -
how can i return tcp in django to confuse nmap?
nmap scan send with the request 0 headers, so if not request.headers: print("nmap scan me") than django send him http response back and nmap know this is http and start http scan but if i send him back tcp connection he cant say that this is a http scan and he wont scan my website however if i do something like return b"hi i return bytes" i get an error so how can i return tcp response instead of http response -
cannot get image to upload to folder in django
I am making a personal training website and am having trouble getting the profile pic to upload my form looks like this: <form class="form-horizontal" action="updateProfile" method="post" enctype= "multipart/form-data"> {% csrf_token %} <div class="form-group"> <label class="control-label col-sm-2" for="gym">Main Gym</label> <div class="col-sm-10"> <input type="text" class="form-control" id="gym" placeholder="Enter gym name" name="gym" id="gym"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="last name">Qualifications</label> <div class="col-sm-10"> <textarea name="qualifications" rows="10" cols="130" name="qualifications" id="qualifications"></textarea> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="last name">About Me</label> <div class="col-sm-10"> <textarea name="aboutme" rows="10" cols="130" id="aboutme"></textarea> </div> <div class="form-group"> <label class="control-label col-sm-2" for="servicedetails">Service Details</label> <div class="col-sm-10"> <textarea name="servicedetails" rows="10" cols="130" id="servicedetails"></textarea> </div> <div class="form-group"> <label for="avatar">Choose a profile picture:</label> <div class="form-group"> <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg"> </div> </div> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Submit</button> </div> </div> </form> models.py: class trainerabout(models.Model): userID = models.IntegerField() gym = models.TextField(max_length=30) qualifications = models.TextField() aboutme = models.TextField() servicedetails = models.TextField() profilepic = models.ImageField(upload_to='images/') added this to urls.py urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py: def updateProfile(request): if request.method == 'POST': gym = request.POST['gym'] qualifications = request.POST['qualifications'] aboutme = request.POST['aboutme'] servicedetails = request.POST['servicedetails'] avatar = request.POST['avatar'] trainer = trainerabout(gym=gym, qualifications=qualifications, aboutme=aboutme, servicedetails=servicedetails, profilepic=avatar, userID=request.user.id) trainer.save() return render(request, 'updateProfile.html') added this to settings.py MEDIA_URL = '/media/' MEDIA_ROOT = … -
Unable to run python file
I have been trying to run a python script, but I keep on getting the following error. Error: Traceback (most recent call last): File "cloud_copasi/background_daemon/cloud_copasi_daemon.py", line 18, in <module> django.setup() File "/Users/cloudcopasi/cloud-copasi/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/cloudcopasi/cloud-copasi/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/cloudcopasi/cloud-copasi/venv/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'web_interface' The script file which I am trying to run (cloud_copasi_daemon) is: import sys, time import django django.setup() from tools.daemon import Daemon import tools.background_script from tools.response import RemoteLoggingResponse from cloud_copasi import settings import logging log=logging.getLogger(__name__) class MyDaemon(Daemon): #Set the level we wish to log at. Logs are sent back to the central server #Choices are all, debug, info, error, none def __init__(self, *args, **kwargs): return super(MyDaemon, self).__init__(*args, **kwargs) def stop(self, *args, **kwargs): return super(MyDaemon, self).stop(*args, **kwargs) def run(self): log.debug('Daemon running') while True: min_repeat_time = settings.DAEMON_POLL_TYME #Seconds start_time = time.time() try: tools.background_script.run() log.debug('Background script finished') except Exception as e: log.exception(e) finish_time = time.time() difference = finish_time - start_time if difference < … -
Recieving plain Js code File in the axios GET Response in react while trying tp get data Using DRF
I have this problem while i was making Get request from my React Frontend to Drf Backend, It was suppose to get the User Details and set it to State when i dispatch using Redux, But the Reponse from backend is a Pure Js code File or index.html file that we suppose to have in build folder while running React With Django . export const load_user = () => async dispatch => { if (localStorage.getItem('access')) { console.log('True') const config = { headers: { 'Content-Type': 'application/json', 'Authorization': `JWT ${localStorage.getItem('access')}`, } }; try { const res = await axios.get(`${process.env.REACT_APP_API_URL}/auth/users/me/`, config); const user_type = res.data.type_of_user.toLowerCase() const id = res.data.id const res1 = await axios.get(`${process.env.REACT_APP_API_URL}/app/${user_type}/${id}`, config) console.log(res1.data) dispatch({ type: USER_LOADED_SUCCESS, payload: res1.data }); } catch (err) { dispatch({ type: USER_LOADED_FAIL }); } } else { dispatch({ type: USER_LOADED_FAIL }); } }; Here is the URLs.py Template view setup for Django to load build file's index.html from django.contrib import admin from django.urls import path, include, re_path from django.views.generic import TemplateView from app.views import index urlpatterns=[ path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), path('app/', include('app.urls')), path("", index ) ] urlpatterns+=[re_path("", TemplateView.as_view(template_name='index.html'))] here is app's urls.py from django.urls import path from .views import PatientView, DoctorView, VitalView, UserView, send_mail_to_doctor, … -
How can I Fix this SQL Syntax error 1064, Where It says to look at the MySQL server version for the right syntax to use?
ERROR : django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':'STRICT_TRANS_TABLES'' at line 1") Code: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'REDACTED', 'USER': 'REDACTED', 'PASSWORD': 'REDACTED', 'HOST': 'REDACTED', 'PORT': 'REDACTED', 'OPTIONS': { 'init_command': "SET sql_mode:'STRICT_TRANS_TABLES'" } } } MySQL Version = mysqlclient : 1.4.6 Server version: 5.7.31 - Gentoo Linux mysql-5.7.31 Protocol version: 10 Help is very appreciated -
Can't connect Django and PostgreSQL (EC2)
I have two servers "App Server" with IP y.y.y.y in which I have a Django Project that I'm trying to connect with another server called "Data Server" with private IP x.x.x.x, I'm getting this error every time I want to make migration: FATAL: no pg_hba.conf entry for host "y.y.y.y", user "usuario1", database "redesproyecto1", SSL off This is my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'redesproyecto1', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'x.x.x.x', 'PORT': '5432', } } And this is my pg_hba.conf: # Database administrative login by Unix domain socket local all postgres ident # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all md5 # IPv4 local connections: host all all 127.0.0.1/32 trust # IPv6 local connections: host all all ::1/128 md5 # Allow replication connections from localhost, by a user with the # replication privilege.l host all all y.y.y.y trust host all postgres 127.0.0.1/32 md5 host all all ::1/128 md5 Am I missing something? -
"Lost connection to MySQL server during query" with venv
I don’t know why. When I don’t use the virtual environment, everything is normal, and the error "Lost connection to MySQL server during query" appears when I use the virtual environment. Python3.6.9 Django2.2 mysql 5.7 Internal Server Error: /sap/base/v1/token_by_code/get_token/ Traceback (most recent call last): File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/db/backends/base/base.py", line 240, in _commit return self.connection.commit() MySQLdb._exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/python3.6/lib/python3.6/contextlib.py", line 52, in inner return func(*args, **kwds) File "/usr/local/python3.6/lib/python3.6/contextlib.py", line 52, in inner return func(*args, **kwds) File "/usr/local/python3.6/lib/python3.6/contextlib.py", line 52, in inner return func(*args, **kwds) File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/db/transaction.py", line 240, in __exit__ connection.commit() File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/db/backends/base/base.py", line 262, in commit self._commit() File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/db/backends/base/base.py", line 240, in _commit return self.connection.commit() File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/db/backends/base/base.py", line 240, in _commit return self.connection.commit() django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query')