Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save record ModelForm with belong to relationship django
I'm trying to adding or change the record in database based on id user, for example if there's no record profile exists from current user then create new one. if I add exists code it's okay because instance is model with get id as user_id Here's the code: models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) name = models.CharField(max_length=171) bank_name = models.CharField(max_length=191, null=True) bank_account = models.CharField(max_length=191, null=True) profile_picture = models.ImageField(upload_to='profile_pics', blank=True) phone_number = models.CharField(max_length=191) description = models.TextField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username @classmethod def get_accounts(cls, user_id): q = cls.objects.filter(user_id=User(pk=user_id)).first() try: return { "id": q.user.id, "username": q.user.username, "name": q.name, "profile_picture": q.profile_picture.url, "phone_number": q.phone_number, "bank_name": q.bank_name, "bank_account": q.bank_account, "description": q.description } except AttributeError as err: raise err.with_traceback(err.__traceback__) forms.py from django import forms from .models import UserProfileInfo class PatchUserProfileForm(forms.ModelForm): class Meta: model = UserProfileInfo fields = ('name', 'phone_number', 'profile_picture', 'description', 'bank_name', 'bank_account') class views.py @method_decorator(csrf_exempt, name='dispatch') class APIAccounts(View): def get(self, requests): if requests.user.is_authenticated: try: return JsonResponse(UserProfileInfo.get_accounts(requests.user.id), status=200) except AttributeError: return JsonResponse({"message": "Access denied"}, status=403) else: return JsonResponse({"message": "Unauthenticated"}, status=401) def post(self, requests): if requests.user.is_authenticated: try: try: data = UserProfileInfo.objects.get(user_id=requests.user.id) form = PatchUserProfileForm(requests.POST, requests.FILES, instance=data) except ObjectDoesNotExist: # … -
validate method not called django rest framework
I am trying to test validate method on modelSerializer but it is NOT CALLED. Why is not working ? Have i been missed something ? the same scenario works at different project at urls urlpatterns = [ path('api/allposts/', allposts, name='allposts') ] at views: from .serializer import PostSerializer from rest_framework.renderers import JSONRenderer from .models import Post from django.http import JsonResponse import json def allposts(request): qs = Post.objects.all()[:3] ser = PostSerializer(qs, many=True) data = JSONRenderer().render(ser.data) return JsonResponse(json.loads(data), safe=False) at models class Post(models.Model): title = models.CharField(max_length=100) url = models.URLField() poster = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.title at serializer from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['title', 'poster', 'url'] def validate(self, data): if 'facebook' in data.get('url'): raise serializers.ValidationError('you can not add facebook') return data -
AbstractUser User With mongoengine in django
I am using mongodb(3.6) in python(3.8.5) django(3.1.5). and i have used djonjo(1.3.3) and mongoengine(0.22.1) for mongoDB. now i have trying to create AbstractUser model with mongoengine`s Document. and also i have create django model with EmbeddedDocument. like - from mongoengine import Document, EmbeddedDocument, fields class UserDepartment(EmbeddedDocument): department = fields.StringField(max_length=250, unique=True) created_at = fields.DateTimeField(default=datetime.now()) updated_at = fields.DateTimeField(default=datetime.now()) so it not adding in migration file and also not creating mongodb collection with this model. so how could i create AbstractUser and EmbeddedDocument model in mongoengine and migrate them -
Unauthorized: /msal/login_with_code/ while using pypi package: drf_msal_jwt
I am trying to implement Azure SSO with Django as Backend and React as Frontend. I was able to implement generate-login-url and login-with-code functionalities with the help of the documentation and it successfully runs in the postman. But implementing the same via react does not give the same result. I inspected the package and in the below code for login class MSALLoginWithCodeView(APIView): authentication_classes = [] permission_classes = [] def post(self, request, format=None): msal_check_state = api_settings.MSAL_CHECK_STATE code_serialized = CodeSerializer(request.data) if msal_check_state and request.session.get('msal_state', '') != code_serialized.data['state']: raise StateException() user_token = get_user_jwt_token(code_serialized.data['code']) return Response({ 'token': user_token }) I am getting different results while checking the same url via postman and my implementation with react. For postman I for the value request.session when i inspect it with request.session.__dict__ I get {'_SessionBase__session_key': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'accessed': True, 'modified': False, 'serializer': <class 'django.core.signing.JSONSerializer'>, 'model': <class 'django.contrib.sessions.models.Session'>, '_session_cache': {'msal_state': 'xxxxxxxx-xxx-xxxx-xxxx-xxxxxxxxxxxx'}} and will work correctly and will return a token, but for react implementation I get {'_SessionBase__session_key': None, 'accessed': False, 'modified': False, 'serializer': <class 'django.core.signing.JSONSerializer'>} What do I need to update? -
How to find models where their member queryset contains another models query set in django
say I have the following models flag user project userflag -user fk -flag fk projectflag -project fk -flag fk what I want is the queryset of users where their set of flags contains the set of flags on a specific project, something like user.objects.filter(project.projectflag_set_in = userflags) -
How to redeem coupon code which i created in django?
I created Coupon code in django rest framework and now i like to redeem it using python script or any frontend method, i don't have way, path or logic which can guide me on how to do it. Here is my models.py file : from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Coupon(models.Model): code = models.CharField(max_length=50, unique=True) valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) active = models.BooleanField() def __str__(self): return self.code here is my serializers.py file from rest_framework import serializers from .models import Coupon class CouponSerializer(serializers.ModelSerializer): class Meta: model = Coupon fields = '__all__' here is my views.py file from django.shortcuts import render from .models import Coupon from .serializers import CouponSerializer from rest_framework import viewsets class CouponViewSet(viewsets.ModelViewSet): queryset = Coupon.objects.all() serializer_class = CouponSerializer Please do help -
I am making an User(AbsrtactUser) model and I need to make a field that auto increments
class CustomUser(AbstractUser): email = models.EmailField(unique=True,blank=True,max_length=254, verbose_name='email address') phone_number = models.IntegerField(blank=True,null=True,verbose_name="phone number") ids = models.UUIDField(blank=True,null=True,default=uuid.uuid4, editable=False) #parent_id = models.IntegerField(blank=True,null=True) role_id = models.IntegerField(null=True,blank=True) How do i create role_id as auto_increment field. I tried making role_id field AutoField but that just gave me an error that we cannot have 2 Autofield in one model and I dont want to make any changes with django default id primary key as i need that field. can we give reference of (id primary key) to (role id)..? -
Changing appearance of 'Remember Me' field for django-allauth+crispy_forms
I want to change the appearance of the "Remember me" checkbox but I can't find a solution that will work. Here is what I have right now: Image Additional info: Django==3.0.11 django-allauth==0.44.0 Running in the Docker Viewed in Chrome Macos Catalina Here is the code in the template: <form class="login" role="form" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} {{ form|crispy }} <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a> {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button class="btn btn-primary shadow-2 mb-4" type="submit" >{% trans "Sign In" %}</button> </form> I have tried to have a nested dict with css styling inside the form (based on this answer), but no luck so far. Here is the form from forms.py: class UserLoginForm(LoginForm): def __init__(self, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) # self.helper.form_show_labels = False # Doesn't work though it should self.fields["login"].label = "" self.fields["password"].label = "" self.fields["remember"].widget.attrs.update({ "div": { "class": "form-group text-left", "div": { "class": "checkbox checkbox-fill d-inline", "input": { "type": "checkbox", "name": "checkbox-fill-1", "id": "checkbox-fill-a1" }, "label": { "for": "checkbox-fill-a1", "class": "cr" } } } }) I do not want to go into the package itself to … -
I have stored the data in json format in Js file. i want to bring it to django.views how can i do that?
I am using Django where i am working with some project. In that i have stored the data in JSON format in JS file i want to render it and bring it to Views for further use.How can i use do it? JS: function save(){ var quizform=[]; quizform.push({quizname: document.getElementById("Quizname").value}); for (var z = 1; z <= container_count; z++) { var obj = new Object(); obj.question = document.getElementById("Q".concat(z.toString())).value; obj.answers = new Object(); obj.answers.a = document.getElementById("Qa".concat(z.toString())).value; obj.answers.b = document.getElementById("Qb".concat(z.toString())).value; obj.answers.c = document.getElementById("Qc".concat(z.toString())).value; obj.answers.d = document.getElementById("Qd".concat(z.toString())).value; obj.answers.e = document.getElementById("Qe".concat(z.toString())).value; obj.correctAnswer = document.getElementById("CorrectOption".concat(z.toString())).value; quizform.push(obj); } var myjson = JSON.stringify(quizform); console.log(myjson); } HTML: {% extends 'base.html' %} {% load static %} {% block content %} <body> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/popup.css'%}"> <div id="FC" class="flex-container"> </div> <div class="buttons"> <button id="add-question" class="add-question">+</button> <button id="save" class="save" method="POST">save</button> </div> <script type="text/javascript" src="{% static 'assets/js/CQ.js'%}"></script> </body> {% endblock %} Views: from django.shortcuts import render,get_object_or_404,redirect from students.models import * def PreviewQuizCreating(request,slug): session=get_object_or_404(Session_Details,slug=slug) context={'session':session} return render(request,'CQ.html',context) I need the variable myjson to my views -
'QuerySet' object has no attribute 'gmail'
I am working with Django. my models.py: class Admin(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, related_name='admin_releted_user') name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) def __str__(self): return self.name Now I am trying to get a list of gmail inside to named variable. in my views.py: def submit_report(request, pk): admin_obj = Admin.objects.all() to = admin_obj.gmail print(to) return redirect('app:index') but it says error like: Internal Server Error: /submit_report/1/ Traceback (most recent call last): File "G:\Python\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "G:\Python\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "G:\Python\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Project\django\hackathon practice\ProjectSurokkhaBeta_1.7\app\views.py", line 532, in submit_report to = admin_obj.gmail AttributeError: 'QuerySet' object has no attribute 'gmail' [12/Jan/2021 09:48:54] "GET /submit_report/1/ HTTP/1.1" 500 77827 How can I fix it? -
TypeError at /order 'datetime.time' object is not callable Django
I want to make estimate making order time in my Django Apps but I am confuse about the time that cannot be calculated. I defined the datetime first then values, so I reduce the datetime - values, which I hope the result is now time reduced by datetime. here is my templatetags\cart.py : @register.filter(name="estimasipending") def estimasipending(datetime): values = (datetime.datetime.today) return datetime - values` here is my Views order.py : from django.shortcuts import render, redirect from django.views import View from store.models import Customer from store.models import Order class OrderView(View): def get(self,request): customer_id = request.session.get('customer') orders = Order.objects.filter(customer=customer_id).order_by("-date").order_by("-id") print(orders) return render(request,'order.html',{"orders":orders})` here is my HTML template {% for order in orders %} <tr> <td>{{ forloop.counter }}</td> <td><img height="80px" width="100px" src="{{ order.product.image.url }}" alt=""></td> <td>{{ order.product }}</td> <td>{{ order.price|currency }}</td> <td>{{ order.quantity }}</td> <th>{{ order.quantity|multipy:order.price|currency }}</th> <th>{{ order.date }}</th> <th>{{ order.datetime }}</th> {% if order.completed %} <th><span class="badge badge-success">Your Order is Ready</span></th> {% elif order.confirmed %} <th><span class="badge badge-success">We are making your order estimate {{ order.datetime|estimasipending }}</span></th> {% else %} <th><span class="badge badge-warning">Pending</span></th> {% endif %} </tr> {% endfor %}` and the error show like this : TypeError at /order 'datetime.time' object is not callable sorry for my bad english, I still learn. -
Django attribute error due to login code and I can't get to run migrate
when I run python manage.py migrate it show error urls.py", line 30, in url(r'^users/login/$', auth.login, {'template_name': 'login.html'}, name='login'), AttributeError: module 'django.contrib.auth.views' has no attribute 'login' I have shown code urls.py and views.py urls.py from django.conf.urls import url from django.contrib import admin from orders import views as my_order from django.contrib.auth import views as auth from django.contrib.auth.decorators import login_required urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', my_order.index, name='home'), url(r'^orders$', my_order.index, name='home'), url(r'^order/(?P<order_id>\d+)/$', my_order.show, name='show'), url(r'^order/new/$', my_order.new, name='new'), url(r'^order/edit/(?P<order_id>\d+)/$', my_order.edit, name='edit'), url(r'^order/delete/(?P<order_id>\d+)/$', my_order.destroy, name='delete'), url(r'^users/login/$', auth.login, {'template_name': 'login.html'}, name='login'), url(r'^users/logout/$', auth.logout, {'next_page': '/'}, name='logout'), url(r'^users/change_password/$', login_required(auth.password_change), {'post_change_redirect' : '/','template_name': 'change_password.html'}, name='change_password'), ] views.py from django.shortcuts import render, redirect from .models import Order from .forms import OrderForm from django.contrib import messages from django.contrib.auth.decorators import login_required @login_required def index(request): orders = Order.objects.all() return render(request, 'index.html', {'orders': orders}) @login_required def show(request, order_id): order = Order.objects.filter(id=order_id) return render(request, 'show.html', {'order': order}) @login_required def new(request): if request.POST: form = OrderForm(request.POST) if form.is_valid(): if form.save(): return redirect('/', messages.success(request, 'Order was successfully created.', 'alert-success')) else: return redirect('/', messages.error(request, 'Data is not saved', 'alert-danger')) else: return redirect('/', messages.error(request, 'Form is not valid', 'alert-danger')) else: form = OrderForm() return render(request, 'new.html', {'form':form}) @login_required def edit(request, order_id): order = Order.objects.get(id=order_id) if request.POST: form = … -
Would these tests be considered unit tests? How do I make an integration test with this?
I'm writing tests for my django rest app and I'm wondering if these are considered unit tests. I was told I should write integration and unit tests but I'm not sure how to test the app with the integration tests (if the tests I've already written are unit tests). This is my test view: from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from todo.models import Task class CreateTaskTest(APITestCase): def setUp(self): self.data = {'title': 'title', 'description': 'desc', 'completed': False} def test_can_create_task(self): response = self.client.post(reverse('task-list'), self.data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) class ListTaskTest(APITestCase): def setUp(self): self.data = {'title': 'title', 'description': 'desc', 'completed': False} def test_can_list_task(self): response = response = self.client.get(reverse('task-list'), self.data) self.assertEqual(response.status_code, status.HTTP_200_OK) class DeleteTaskTest(APITestCase): def setUp(self): self.data = Task.objects.create(title= 'title', description= 'desc', completed= False) def test_can_delete_task(self): response = self.client.delete(reverse('task-detail', args=(self.data.pk,))) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) class RetrieveTaskDetailsTest(APITestCase): def setUp(self): self.data = Task.objects.create(title= 'title', description= 'desc', completed= False) def test_can_retrieve_task_details(self): response = self.client.get(reverse('task-detail', args=(self.data.pk,))) self.assertEqual(response.status_code, status.HTTP_200_OK) This is my view: from rest_framework import generics, filters from todo import models from .serializers import TaskSerializer from django_filters.rest_framework import DjangoFilterBackend class ListTask(generics.ListCreateAPIView): """ API view to retrieve list of tasks or create new tasks """ queryset = models.Task.objects.all() serializer_class = TaskSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = … -
Django Rest Serializer Nested Fields
I am attempting to do a double nested response but the code isn't working. I am retrieving my objects by a filter with a field and not an id or pk. Probably unneeded but on the frontend i use {this.state.profiles[0].title} as there will ever only be one response since the slug field i use to query is a unique field in the database. In the VideoProduct(models.Model) below, I have profile OneToOneField. I have that as a tester to see if i could just get a nested response, but that wouldn't work either. Models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class VideoProduct(models.Model): profile = models.OneToOneField(Profile, on_delete=models.CASCADE) ... class ProfileProduct(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) video_product = models.ForeignKey(VideoProduct, on_delete=models.CASCADE, blank=True) class Meta: unique_together = ('profile', 'video_product') Views.py: class VideoProductViewSet(viewsets.ModelViewSet): queryset = VideoProduct.objects.all() serializer_class = VideoProductSerializer class ProfileProductsViewSet(viewsets.ModelViewSet): queryset = ProfileProduct.objects.all() serializer_class = ProfileProductsSerializer class ProfileBySlug(generics.ListAPIView): serializer_class = ProfileBySlugSerializer def get_queryset(self): slug = self.request.query_params.get('slug', None) queryset = Profile.objects.filter(slug=slug) if slug is not None: queryset = queryset.filter(slug=slug) return queryset Serializers: class VideoProductSerializer(serializers.ModelSerializer): class Meta: model = VideoProduct fields = ['id'] class ProfileProductsSerializer(serializers.ModelSerializer): video_product = VideoProductSerializer(read_only=True) class Meta: model = ProfileProduct fields = ['id', 'video_product'] class ProfileBySlugSerializer(serializers.ModelSerializer): profile_products = ProfileProductsSerializer(many=True, read_only=True) class Meta: model = Profile … -
Docker, Django, Gunicorn, and Nginx: 403 Forbidden (13: Permission denied)
I've been having difficulty dockerizing Django with Gunicorn and Nginx. I'm new to Docker, and I could seriously use the help. My pages load, but all of the static files return something like: nginx_1 | 2021/01/12 02:08:24 [error] 21#21: *7 open() "/app/static/img/favicon.ico" failed (13: Permission denied), client: 172.18.0.1, server: , request: "GET /static/img/favicon.ico HTTP/1.1", host: "localhost:8000", referrer: "http://localhost:8000/login/" While I've read that there are a few other reasons for this error, my suspicion is that I need to set up a non-root user and configure file permissions in my Dockerfile. I've tried this approach, although I wasn't successful. Here's a few of my files. Hopefully, this helps. If there's anything else I need to provide, please let me know. Thanks! Dockerfile: FROM python:3.6.9-alpine ENV PYTHONUNBUFFERED 1 RUN apk add --no-cache --upgrade gcc musl-dev python3-dev libffi-dev openssl-dev RUN pip install --upgrade pip COPY ./PW_Purchasing/requirements.txt /requirements.txt RUN pip install -r requirements.txt WORKDIR /app ADD ./PW_Purchasing /app/ EXPOSE 8000 CMD ["gunicorn", "--chdir", "PW_Purchasing", "--bind", ":8000", "PW_Purchasing.wsgi:application"] docker-compose.yml: version: "3.9" services: web: build: . volumes: - .:/app - static_volume:/app/static networks: - nginx_network nginx: image: nginx:1.19.0-alpine ports: - 8000:80 volumes: - static_volume:/app/static - ./config/nginx/conf.d:/etc/nginx/conf.d depends_on: - web networks: - nginx_network networks: nginx_network: driver: bridge volumes: … -
Building an email client with Python/Django - Storing users mails
I want to build an email client webApp using Django/Python, so that Outlook users can connect to it and send/receive emails. I have used MSAL (the Microsoft identity platform endpoint in order to authenticate users and access secured web APIs) to get token with the OAuth standard. In order to store users emails and sync them, I have thought of storing the Token in server-side and create a process that runs every 15 min to get updates from outlook users accounts (new received email, new sent email ...) and store them in MongoDB Atlas. I don't think this is the good way to do it since the token have to be on client side. Can anyone please suggest a more secure and efficient way to do it ? Thank you very much ! -
UserCreationForm not validating if passwords are the same - Django
I am running registration using a custom user model and UserCreationForm. My understanding is that UserCreationForm should be validating that the two passwords are the same. This isn't happening on my form. I have tried with and without crispy and it still isn't working. I am able to submit my form with two mismatched passwords however since the form isn't valid nothing saves. Not sure what to try next. Any help appreciated. forms.py class RegisterForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for fieldname in ['password1', 'password2']: self.fields[fieldname].help_text = None self.helper = FormHelper() self.form_methd = 'POST' self.helper.form_id = 'RegisterForm' self.fields['termsandcon'].required = True self.fields['first_name'].required = True self.fields['last_name'].required = True self.fields['company_name'].required = True self.fields['job_title'].required = True self.helper.layout = Layout( Row( Column(PrependedText( 'email', "", placeholder="barry@ausyn.io"), css_class='form-group mb-0'), ), Row( Column(PrependedText( 'first_name', "", placeholder="Barry"), css_class='form-group mb-0'), Column(PrependedText( 'last_name', "", placeholder="Ausyn"), css_class='form-group mb-0'), ), 'password1', 'password2', Row( Column(PrependedText( 'company_name', "", placeholder="Ausyn"), css_class='form-group col-md-6 mb-0'), Column(PrependedText( 'job_title', "", placeholder="Music Supervisor"), css_class='form-group col-md-6 mb-0'), ), Row('termsandcon', HTML( """<span>I accept the <a href="#">Terms and Conditions</a></span>"""),), Column(Submit( 'submit', 'Sign Up', css_class='btn btn-primary'), css_class="form-group mb-0 text-center") ) class Meta: model = User fields = [ 'email', 'first_name', 'last_name', 'termsandcon', 'company_name', 'job_title', ] labels = {'termsandcon': '', } models.py - customuser class … -
DJANGO: CSS not loading adter trying other threads
I am having major issues with my css not loading in my Django Project. It is just a simple project for now as I have just started and when I tried to recreate my normal website the css will no load. I am using render() to load the files in the views.py Here I have attached some of the files that I think are important - please request others if needed BASE.html {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/csss" href="{% static 'homepage/main.css' %}"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> {% if title %} <link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet"> <title>SW - {{title}}</title> {% else %} <title>SW</title> {% endif %} </head> <body> <nav> <ul> <li><a href='index.html'>HOME</a></li> <li><a href='#'>ABOUT ME</a></li> <li><a href="#">GALLERY</a></li> <li><a href="https://github.com/Wxshy/Code">CODE</a></li> <li><a href='#'>FEEDBACK</a></li> </ul> </nav> <main role='main' class="container"> {%block content%}{%endblock%} </main> </body> </html> HOMEPAGE.html {% extends "homepage/base.html" %} {%block content%} <svg width="461" height="295" viewBox="0 0 461 295" fill="none" xmlns="http://www.w3.org/2000/svg" id="logo"> <path d="M59.744 79.368C59.744 75.336 58.544 72.072 56.144 69.576C53.744 66.984 50.72 64.728 47.072 62.808C43.52 60.792 39.632 58.92 35.408 57.192C31.184 55.464 27.248 53.4 23.6 51C20.048 48.504 17.072 45.48 14.672 41.928C12.272 38.28 11.072 33.672 11.072 28.104C11.072 20.232 13.808 13.992 19.28 9.38398C24.752 4.77598 32.528 2.47198 42.608 2.47198C48.464 2.47198 53.792 2.90398 … -
Realtime messenger app with Django and Cloud Firestore - how to send data to the frontend
How would I setup a server architecture to read/write from Cloud Firestore and update a single page in realtime? Cloud Firestore has an on_snapshot method which listens to changes in the database already and allows me to see realtime changes to a collection/document. So I don't need a backend module which connects to the Firestore database. I do, however, need something which allows the frontend UI to establish a connection to my backend to retrieve the data and display it. Is this what django-channels is for? In which case, what would my stack look like? How would I get the frontend to connect to the server backend? Javascript --> Websocket to Server Backend <-- Server Backend <-- Firestore DB Listener <--- Cloud Firestore Also, since the Messenger will have multiple chats open at the same time, there will be multiple threads listening to different collections. Do I need to use Javascript multithreading as well to accomplish listening to those db connection threads? I would prefer to use the least amount of Javascript possible and the most amount of python possible. -
How would you create multiple logins from 1 set of credentials
Here is the scenario: Say I have a Netflix account and I want to share it with my friends so they use it too but I don't want to share the exact password because I'm worried someone will change it (don't share your password if you don't trust your friends right... just an example, but you get the point). Is it possible to create "sub-admins" of the account with certain privileges if the web-app doesn't allow for it? Let me know if this makes sense. -
Nginx connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.128.1, server: hello-1.local
I am trying to setup ssl on my django + docker + nginx environment. However I encountered this error: *19 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.128.1, server: hello-1.local, request: "GET / HTTP/1.1", upstream: "https://192.168.128.4:443/", host: "hello-1.local" My Nginx config: client_max_body_size 10M; upstream web { ip_hash; server web:443; } server { listen 80; server_name hello-1.local; return 301 https://$host$request_uri; } server { location /static/ { autoindex on; alias /src/static/; } location /media/ { autoindex on; alias /src/media/; } `` location / { proxy_pass https://web/; } listen 443 ssl; server_name hello-1.local; ssl_certificate /etc/certs/hello-1.local.crt; ssl_certificate_key /etc/certs/hello-1.local.key; } Yaml: version: "3" volumes: local_postgres_data: {} local_postgres_data_backups: {} services: nginx: image: nginx:alpine container_name: nz01 ports: - 443:443 - 80:80 volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d - ./config/certs:/etc/certs depends_on: - web networks: - djangonetwork web: build: context: . dockerfile: compose/django/Dockerfile container_name: dz01 depends_on: - db volumes: - ./src:/src expose: - 8000 links: - redis env_file: - ./.envs/.django networks: - djangonetwork db: build: context: . dockerfile: compose/postgres/Dockerfile container_name: pz01 env_file: - ./.envs/.postgres volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups networks: - djangonetwork redis: image: redis:alpine container_name: rz01 ports: - "6379:6379" networks: - djangonetwork networks: djangonetwork: driver: bridge In browser, I get 502 Bad Gateway error and without … -
Can I send the computed result in the background task in Django to the frontend (Angular)?
In the Django view, I have used the multiprocessing module of python and have successfully made parallel requests to Julia's server using the map function of the multiprocessing module. The result is automatically given as a list to the view and I return the results list to Frontend using HTTP response. However, Julia takes nearly 10 minutes to compute 1 task and even after parallel processing it consumes a lot of time and the frontend has to wait way too long for the final response to come through. So for each call to Julia, I need to send the computed result back to the frontend so it can start working on this data. I do not want to use Celery. Any ideas on how to send HTTP requests to the frontend from the subprocesses themselves? -
Django Admin 'login as' button
On user form view, add button "Login As", that button will execute functionality that we login as that user. Only admins can see/execute this functionality. This is my question, how this to make? Can someone help me with this task -
No 'Access-Control-Allow-Origin' on Django/AWS access for manifest.json
I am hosting a Django(Heroku) app and I am hosting the static files on S3(AWS) and I keep getting: Access to manifest at 'https://solutions-web.s3.amazonaws.com/static/manifest.json' from origin 'https://solutions-web.herokuapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. On my AWS Cross-origin resource sharing (CORS) I have [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [], "MaxAgeSeconds": 3000 } ] and I am calling it from the index.html as ... <link rel="manifest" href="{%static 'manifest.json'%}" /> ... And I have the following in my settings.py CORS_ALLOWED_ORIGINS = ["http://localhost:8000", "https://solutions-web.herokuapp.com"] ALLOWED_HOSTS = ["127.0.0.1", "localhost", "solutions-web.herokuapp.com"] STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) All the other static files are working normally as expected except the manifest.json What do I do? -
Javascript display block not displaying successfully because of django condition
By default, request.user.enlazado = True Then, Without page reloading I am setting request.user.enlazado = False Then, this line of code gets executed: document.querySelector('#enlazacion').style.display = 'block'; And this is my html: <section id="enlazacion"> {% if request.user.enlazado is False %} <h3>Enlaza</h3> {% endif %} </section> The problem is that, as I'm not reloading the page, the front-end still thinks that request.user.enlazado is True, while in the server it has already been changed to False. That style.display = 'block' is not displaying it's content as a result. Is there a way to override this Django html condition?