Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models from other project
Currently I have a Django project for an Online Shop. It has many models like Order, Product and others. This project is relatively big and has 40+ models and more than 8 apps. Now I need to create an Admin platform for the shop. In this platform I must be able to see all the orders made by all users, all the companies which sell their products in my shop and a lot of other data. Obviously, it must use the same database the shop uses which leads me to using the same models to work with the data as the Shop project uses. This is where I have a problem. Somehow I need to get access to models from Shop project in the Admin project. I see several solutions: To create a pip package from my Shop project and import it in the Admin project. However, my shop project is still in active development and I make changes to its code very frequently, so, I will have to rebuild and reinstall it every time I make the changes. Considering this I think that this isn't the option. Use Shop's API in Admin project. By this I mean that I … -
Forbidden (CSRF token missing or incorrect.): Django form
I'm trying to subscribe an email account into a newsletter using Django, when I try to click the Go button I get the error Forbidden (CSRF token missing or incorrect.): Here is the views.py method: def newsletterSubscribe(request): try: form = NewsletterUserSignUpForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if NewsletterUser.objects.filter(email=instance.email).exists(): messages.warning(request, _('Alerta! El correo ingresado ya se encuentra suscrito.'), 'alert alert-warning alert-dismissible') else: instance.save() messages.success(request, _('Correo agregado con exito!'), 'alert alert-success alert-dismissible') subject = _('Gracias por unirse a nuestro boletín') message = _("""Bienvenido al boletín de ADA Robotics. Si deseas no estar suscrito visita: https://127.0.0.1:8000/unsubscribed""") msg = MIMEMultipart('alternative') msg['From'] = settings.EMAIL_HOST_USER msg['To'] = instance.email msg['Subject'] = subject part = MIMEText(message, 'plain') msg.attach(part) mail = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT, timeout=20) mail.starttls() """ template = get_template("myapp/sample_template.html") context = Context(context_data) body_html = template.render(context_data) body_text = strip_tags(body_html) part1 = MIMEText(body_text, 'plain') part2 = MIMEText(body_html, 'html') msg.attach(part1) msg.attach(part2) """ emailto = [instance.email] mail.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD) mail.sendmail(settings.EMAIL_HOST_USER, emailto, msg.as_string()) mail.quit() """from_email = settings.EMAIL_HOST_USER to_email = [instance.email] send_mail(subject=subject, from_email=from_email, recipient_list=to_email, message=message, fail_silently=False)""" context = { 'form': form, } template = 'subscribed.html' #return HttpResponseRedirect(request.META.get('HTTP_REFERER')) return render(request, template) except Exception as ex: return render(request, '404.html') Here is the template code: <form id="newsletterForm" action="{% url "newsletterSubscribe" %}" method="POST" class="mr-4 mb-3 mb-md-0"> {% csrf_token … -
Custom calculated column in django_tables2 with one value from html form a the other from database
I am new to Django and currently trying to make a table in django_tables2 with a columns which would display a value from databes(in this case v_pole,v_les,v_celkem) and value from text input in form (cena) multiplied together. After choosing the generovat option in views.py site will take you to pozemky url where the second table with those calculations shuld be generated. [v_pole,v_les,v_celkem are actually values of acreage of field and the "cena" is price which would user set to a certain number] Any valuable information on direction to take would be welcome, thanks. #models.py class Majitele(models.Model): lv = models.IntegerField() katastr = models.CharField(max_length=40) jmeno = models.CharField(max_length=40) ulice = models.CharField(max_length=30) mesto = models.CharField(max_length=30) psc = models.IntegerField() v_pole = models.DecimalField(decimal_places=4, max_digits=10) v_les = models.DecimalField(decimal_places=4, max_digits=10) v_celkem = models.DecimalField(decimal_places=4, max_digits=10) cena_pole = models.IntegerField() cena_les = models.IntegerField() cena_rok = models.IntegerField() nevyplaceno = models.IntegerField() podil = models.CharField(max_length=5) hlasu = models.IntegerField() poznamka = models.CharField(max_length=200) prezence = models.BooleanField() vyplatni = models.BooleanField() postou = models.BooleanField() osobne = models.BooleanField() #urls.py urlpatterns = [ path('admin/', admin.site.urls), path('base/', base_view, name='base'), path('', majitele_view_post, name='tab1_post' ), path('', majitele_view_get, name='tab1_get' ), path('pozemky/', pozemky_view_post, name='tab2_post'), path('pozemky/', pozemky_view_get, name='tab2_get'), ] #views.py def majitele_view_get(request): if request.method == "GET": table = MajiteleTable(Majitele.objects.all()) return render(request, 'tabrender.html', context={'table': table}) def majitele_view_post(request): … -
Not able to post to Django REST API
I wanted to create the ViewSet which return list of objects when doing GET request, and in case POST request it will execute the function and only after this will return this list. I did this like in the documentation, but receiving that "post" is not allowed. views.py class CloudViewSetHosts(viewsets.ModelViewSet): queryset = CloudModelHost.objects.all() serializer_class = CloudSerializerHosts @action(methods=['POST'], detail=True, url_path='autodiscovery', url_name='autodiscovery') def autodiscovery(self, request, requestDataName=None): ... some actions ... return CloudModelHost.objects.all() urls.py router = routers.DefaultRouter() router.register(r'hosts', CloudViewSetHosts) urlpatterns = [ path('', include(router.urls)), ] And curl out : curl -X POST -H 'Accept: application/json; indent=4' http://IP/api/hosts/test/ -vvv * Trying IP:80... * TCP_NODELAY set * Connected to IP (IP) port 80 (#0) POST /api/hosts/test/ HTTP/1.1 Host: IP User-Agent: curl/7.65.3 Accept: application/json; indent=4 Mark bundle as not supporting multiuse < HTTP/1.1 405 Method Not Allowed < Date: Tue, 03 Mar 2020 19:20:38 GMT < Server: Apache/2.4.41 (Ubuntu) < Content-Length: 48 < Vary: Accept < Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS < X-Frame-Options: DENY < X-Content-Type-Options: nosniff < Content-Type: application/json < { "detail": "Method \"POST\" not allowed." Connection #0 to host IP left intact -
inlineformset_factory shows empty dropdown for id_modelname
when creating a formset from a fromset_factory, I get an empty dropdown menu for the model id. How to prevent django from doing this? Related code: Experience model class Experience(models.Model): hnuser = models.ForeignKey(HNuser, on_delete=models.CASCADE, blank=True, default='') activity = models.CharField(max_length=30, null=True, blank=True, default='') campaign = models.CharField(max_length=30, null=True, blank=True, default='') location = models.CharField(max_length=30, null=True, blank=True, default='') year = models.CharField(max_length=4, null=True, blank=True, default='') def __str__(self): return '' class Meta: ordering = ['-year'] verbose_name_plural = 'Experiences' Related HNuser model: class HNuser(AbstractUser): username = None # Make the email field required and unique email = models.EmailField('email address', unique=True) # Set the USERNAME_FIELD--which defines the unique identifier for the User model--to email USERNAME_FIELD = 'email' # additional required fields REQUIRED_FIELDS = [] # Specified that all objects for the class come from the CustomUserManager objects = HNuserManager() def __str__(self): return str(self.id) To be short, in view.py I did this exp_form = ExpFormSet(instance=HNuser.objects.get(pk=user_id)) return render(request,'users/edit_profile.html', { 'exp_form':exp_form, }) And in the template <table class="table"> {{exp_form}} </table> I tried to exclude the field 'id_experiences' in exp_form definition. But since it is not an Experience model attribute, this didn't work. Is anybody out there with an idea what is going on? Any hint is appreciated. -
How to run django migrations when deploying to google app engine from bitbucket pipeline?
I am trying to setup pipelines on bitbucket for my django project. I am using the google-app-engine pipe on bitbucket. But I don't exactly know how I can run my migrations to google cloud sql. -
hide database credentials from template javascript in django
I'm interfacing my Django application with a Neo4J database. I use both the python interface in backend to pass some data to a template with views.py, in this case the credentials are automatically catched from settings. from neo4j import GraphDatabase driver = GraphDatabase.driver(settings.NEO4J_URI, auth=(settings.NEO4J_USERNAME, settings.NEO4J_PASSWORD)) But in other cases, in order to allow more interactivity, I have some tables completely built in javascript, using the neo4j javascrips drivers. In this case, during development I was just creating the driver, with username and password hardcoded inside the script in the head of the template. Now I'm in a more advanced stage of development and I'm of course worried of having username and password in clear in the source code, I can see it quite easily on chrome browser with the "inspect" button. I seen some people suggest just to uglify it, however this is quite risky and I would really like to avoid it. Is there a way to retrieve the driver credentials from backend in order to make them not visible in the code? I also seen this package, would it work in my case? https://pypi.org/project/django-javascript-settings/ I did some research on the topic, however I'm looking for some suggestions as … -
How to implement followers/following using ManyToManyField in Django?
I want to implement the following feature using manytomanyfield in my Django Application. I have created UserProfile class for every user with two attributes: user and follows. User inherit the default Django user model. class UserProfile(models.Model): user = models.OneToOneField(User, related_name = 'user', on_delete=models.CASCADE) follows = models.ManyToManyField("self", related_name = 'follower',symmetrical=False ) I tried this in python shell: >>> lily = User(username="Lily") >>> lily.save() >>> mary = User(username="Mary") >>> mary.save() >>> lily_profile = UserProfile(user=lily) >>> lily_profile.save() >>> mary_profile = UserProfile(user=mary) >>> mary_profile.save() >>> lily_profile.follows.add(mary_profile) But I got this error after I do lily_profile.follows.add(mary_profile) : django.db.utils.OperationalError: table polls_userprofile_follows has no column named from_userprofile_id Does anyone know how to fix this error? Thanks a lot! -
Django not redirecting to next page
I don't know what's happening with my code, once a user that is not authenticated tries to access a page and it redirects to the login page, I can see the next parameter in the browser but after the user logins, it takes the user to the default LOGIN_REDIRECT_URL and not the next page. Also on the template next returns none, so seems the template is not getting thee next value, but in the url it shows the /?next=, thanks in advance. urls.py from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from blog import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.HomeView.as_view(),name="index"), path('accounts/login/', auth_views.LoginView.as_view(), name='login'), path('accounts/logout/', auth_views.LogoutView.as_view(next_page='/'), name='logout'), path('accounts/profile/', views.ProfileView.as_view(), name='profile'), ] registration/login.html {% extends 'app/base.html' %} {% block link %} id="active" {%endblock%} {% block content %} <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <div class="jumbotron" id="font"> {% if next %} {% if user.is_authenticated %} <h2 class="customtext" align="center">Your account doesn't have access to this page. To proceed, please login with an account that has access.</h2> {% else %} <h2 class="customtext" align="center">Please login.</h2> {% endif %} {% else %} <h2 class="customtext" align="center">Enter your login details.</h2> {% endif %} <form action="{% url 'login' %}" method="POST"> … -
Docker Setup Issue
while setting my project on windows 10 home using docker I am getting this error ERROR: for django Cannot start service django: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"./docker/wait-for-it.sh\": stat ./docker/wait-for-it.sh: no such file or directory": unknown ERROR: Encountered errors while bringing up the project. https://i.stack.imgur.com/q6LJm.png https://i.stack.imgur.com/V6oCz.png https://i.stack.imgur.com/92b9z.png -
Django return format_html
I have a function to return an result in an html_format, but I can´t figure out how to return the value in a dynamic way. Currently this is what I have: this is the function: class ImageColumn(tables.Column): def render(self, value): return format_html('<a href="/media/{}" download>Imagen</a>', value) As you can see I have the value 'Image' hardcoded, but what I want is the name of the Image, something like this 'CFE.jpg' to be shown. I have tried this: return format_html('<a href="/media/{}" download>{}</a>', value) but I get a Index Tuple error also I have tried: return format_html('<a href="/media/{}" download>{{object.id}}</a>', value) but in the front end it only shows a '{}' -
Why django gives me this get error while making my first poll apps
I was following this tutorial: "https://docs.djangoproject.com/es/3.0/intro/tutorial03/", and it was all good until this part, where I encountered this error. django error mysite/urls from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls', include('polls.urls')), path('admin/', admin.site.urls), ] mysite/polls/models import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text mysite/polls/urls from django.urls import path from . import views urlpatterns = [ # ex: /polls/ path('', views.index, name='index'), # ex: /polls/5/ path('<int:question_id>/', views.detail, name='detail'), # ex: /polls/5/results/ path('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ path('<int:question_id>/vote/', views.vote, name='vote'), ] mysite/polls/views from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello world, this is Hernán.") def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) and at mysite/settings is all default, except I changed this TIME_ZONE = 'America/Belem' I hope you guys can help me, … -
Django: 'User' object has no attribute 'perfil_de_usuario'
I'm trying to make a page that, after the user is logued in, shows a list of diferent actions. The proble is that, when the user is succesfully authenticated, the resulting page is this error: AttributeError at /iniciar_sesion/ 'User' object has no attribute 'perfil_de_usuario' Request Method: POST Request URL: http://127.0.0.1:8000/iniciar_sesion/ Django Version: 3.0.3 Exception Type: AttributeError Exception Value: 'User' object has no attribute 'perfil_de_usuario' Exception Location: /home/jenifer/Documentos/qbit/mysite4/usuarios/models.py in guardar_usuario_perfil, line 25 The model is as follows: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Perfil_de_Usuario(models.Model): idusuario = models.AutoField(db_column='idUsuario', primary_key=True) nombres = models.CharField(max_length=45, blank=True, null=True) apellidos = models.CharField(max_length=45, blank=True, null=True) clave = models.CharField(max_length=45, blank=True, null=True) email = models.CharField(max_length=45, blank=True, null=True) web = models.URLField(blank=True) class Meta: managed = False db_table = 'Usuario' @receiver(post_save, sender=User) def crear_usuario_perfil(sender, instance, created, **kwargs): if created: perfil_de_usuario.objects.create(usuario=instance) @receiver(post_save, sender=User) def guardar_usuario_perfil(sender, instance, **kwargs): instance.perfil_de_usuario.save() For what the error says, the problem is with guardar_usuario_perfil, but I'm not getting how to modify it for this thing to work. I know there are similar posts and I've tried different solutions like rename instance.perfil_de_usuario.save() part but the result is the same. If somebody can help me I will apreciate it very … -
Textinput not displaying on HTML page
class NewDeviceWidget(MultiWidget): def __init__(self, attrs=None, admin=False): self.attrs = attrs self.admin = admin widgets = ( TextInput(), # device_type TextInput(), # os_type TextInput(), # bitness TextInput(), # file_system ) if self.admin: widgets = widgets + (CheckboxInput(attrs={'value': False}),) # add device to database? super(NewDeviceWidget, self).__init__(widgets, attrs) def decompress(self, value): # decompress stored database format to HTML form format if value: value = json.loads(value) if self.admin: return value return value[:len(value)-1] # return all but the last element return "" def render(self, name, value, attrs=None): # formats the fields to be displayed horizontally context = {'fields': self.widgets} return render_to_string('tifact/widgets/newdevicewidget.html', context) Its not displaying textinputs, instead it is displaying <django.forms.widgets.TextInput object at 0x7ff13ca89470> ... The newdevicewidget html is below too.I am on django 2.2 and python 3.6.9 </br><table style="width:100%"><tr><td>Device Type</td><td>OS Type</td><td>Bitness</td><td>File System</td></tr> <tr> {% for field in fields %} <td>{{ field }}{% if forloop.counter0 == 4 %} Add this device to the database?{% endif %}</td> {% endfor %} </tr></table> -
Django: how to set custom pagination in restapi?
i recently followed django custom pagination(pagination-link). here i tried something in my code but it's showing empty pages(usually nothing result). i am not sure where i made mistake, i usually feel stupid. class Order_ListAPIView(APIView): def get(self,request,format=None): totalData=[] if request.method == 'GET': cur,conn = connection() order_query = ''' SELECT * FROM orders''' order_detail_query = ''' SELECT * FROM order_details ''' with conn.cursor(MySQLdb.cursors.DictCursor) as cursor: cursor.execute(order_detail_query) order_detail_result = cursor.fetchall() order_detail_data = list(order_detail_result) # print(order_detail_data) cursor.execute(order_query) order_result = cursor.fetchall() order_data = list(order_result) dic = {} def merge_order_data_and_detail(order_data, order_detail_data): for d in order_detail_data: if d['order_id'] not in dic: dic[d['order_id']] = [] dic[d['order_id']].append(d) for o in order_data: if o['order_id'] in dic: o['order_detail_data'] = dic[o['order_id']] merge_order_data_and_detail(order_data, order_detail_data) def page_list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) totalData.append({"order_data":order_data, }) return Response({"totalData":totalData,},status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) -
Could not import Django, working last week
This was working last week, when running python manage.py runserver 8080 I get this new error, a week after it was working fine. Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
ForeignKey to AnonymousUser
I would like to follow this guideline and avoid a nullable ForeignKey. I have a ForeignKey to the django User model. If I try to store request.user in an instance of this model, I get this error: ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser>>": "MyModel.user" must be a "User" instance. I think it is feasible to avoid the non-conditionless data schema (nullable foreign key). How could I solve this? -
how to easily pass from django views to django-rest-framework views
I created a nice Django app, anything worked perfectly. Unfortunely I have now to QUICKLY migrate everything to django-rest-framework and to a VUE frontend. I'm in "charge" just of the backend side, someone else will write the frontend code. The problem is that I have really complex Django views and I can't figure out how to change them correctly and easily and, most important, how to test them without a frontend. Have you got any idea how to help? anything would be appreciated!!!!! -
How do you call the default add user form for a custom admin
I created a customized User Admin change form but when I create a new user it goes to the Change form. The Base Admin add form meets what I want hence why I want to keep it? Also how do I encrypt the password once I reverted back to the Base admin create form? How do I change this? Admin.py: from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .forms import UserAdminChangeForm from .models import User # Register your models here. User=get_user_model() class UserAdmin(admin.ModelAdmin): form = UserAdminChangeForm search_fields=['username','user_type'] list_display=('username','full_name','password','email','user_type','ad','pqa','ts','tl','tm','stm','active') list_filter = ('ad',) fieldsets = ( (None, {'fields': ('username', 'password')}), ('Personal info', {'fields': ('full_name','birth_date','hire_date',)}), ('Permissions', {'fields': ('ad','tm','pqa','stm','ts','tl')}), ) class Meta: model = User admin.site.register(User,UserAdmin) forms.py: from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import User class RegisterForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) usertype= forms.Select(choices=User.USER_TYPE_CHOICES) class Meta: model = User fields = ('username',) def clean_username(self): username = self.cleaned_data.get('username') qs = User.objects.filter(username=username) if qs.exists(): raise forms.ValidationError("Username is taken") return username def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") … -
how to generate builtin model permissions for non-managed models?
I have model like this: class Venue(models.Model): name = models.CharField(max_length=255) class Meta: managed = False db_table = 'venue' permissions = [ ('change_venue', 'Can change venue'), ] It is not managed because it already exists in the database (which was created before django project). I want to use django's builtin model permissions, but they are not created by default. I tried to add them by changing Meta.permissions field but got an error: The permission codenamed 'change_venue' clashes with a builtin permission for model 'events.Venue' What should I do? Just make migration and create permissions manually? -
How do I do atomic updates to a directory?
I have a directory with some files in it (they're mostly images with a JSON file). I want to process those files, possibly overwrite some of them and possibly create some new files from some other source. I can have an error happen at any point in this process. How do I ensure that if an error occurs as I'm processing one of the files that I won't end up with the directory in a weird state? I want to only change the contents of the directory if everything went well. Should I create a temporary directory with tempfile.mkdtemp, put my code in a try, do my update in the "temporary" directory, swap the existing directory with the temporary directory, and delete the temporary directory if it still exists in the finally? I'm using Python (Django). -
Format_output not working, and not rendering the page
SO I got application written in django 1.8 and migrating to django 2.2 def format_output(self, rendered_widgets): # formats the fields to be displayed horizontally context = {'fields': rendered_widgets} return render_to_string('tifact/widgets/newdevicewidget.html', context) THis piece of code is no more working, and i read format output disappaered from djanhgo 2.2 I Am trying to get alternate solution to make that work? anyone can help? Thank You -
Python/Django How to find img tag in response using assertContains
I am writing a test. I need to find the img tag on the post page in Django. How to do it ? I'll beat it like that, but it doesn’t work out. Tag not found. with open('media/posts/starlink4_website_Qhna5v6.jpg', 'rb') as fp: self.client.post('/new/', {'text': 'test post with image oh-ye', 'image': 'fp', 'author': 'agent007'}) def test_image_post(self): response = self.client.get('/agent007/1/') self.assertContains(response, '<img ', html=True, status_code=200) -
django-allauth not working with apache2+wsgi
I am using Django 1.8 on python3.6 with virtualenv , trying to integrate google login with django-allauth 0.23.0.it is working fine fine on python3 server (python3 manage.py runserver) but gives below error on production server(apache2+wsgi) ***Social Network Login Failure An error occurred while attempting to login via your social network account. Code: unknown, Error: Error retrieving access token: b'{\n "error": "invalid_scope",\n "error_description": "Some requested scopes were invalid. {valid\\u003d[https://www.googleapis.com/auth/userinfo.profile, https://www.googleapis.com/auth/userinfo.email, openid], invalid\\u003d[https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email, https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile]}",\n "error_uri": "http://code.google.com/apis/accounts/docs/OAuth2.html"\n}'*** the installed apps are given bellow asgiref==3.2.3 certifi==2019.11.28 chardet==3.0.4 confusable-homoglyphs==3.2.0 defusedxml==0.6.0 Django==1.8 django-allauth==0.23.0 django-crispy-forms==1.8.1 django-registration==2.0 idna==2.9 mysqlclient==1.4.6 oauthlib==3.1.0 python3-openid==3.1.0 pytz==2019.3 requests==2.23.0 requests-oauthlib==1.3.0 sqlparse==0.3.0 urllib3==1.25.8 the setting.py file included bellow INSTALLED_APPS = ( #django apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', #third party apps 'crispy_forms', 'registration', # 'custom_user', #my app # 'login', 'newsletter', 'accounts', # #social login 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', ) AUTHENTICATION_BACKENDS = [ 'accounts.backends.EmailBackend', 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', # 'allauth.account.auth_backends.AuthenticationBackend', ] # AUTH_USER_MODEL = 'auth.User' # AUTH_USER_MODEL = 'custom_user.EmailUser' MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'tryDjango18.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(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', 'django.template.context_processors.request', ], … -
is it possible to communicate through socket with django
Hello i have a server program in python built with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) I have to make a web application for the users. the web application must send a string to the server. my question is : Can i use django to build a web application, and send a string to the python server ? thank you for reading.