Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Translate Django group name
I am creating a Django application where users will have different possible groups to manage their permissions. I would like this application to be translatable in the future, but the group names are not translatable by default. How can I make this possible? I have thought about a few possible solutions, but I can't decide which one is best. Replace the template where the groups are displayed and translate the group names. Replace the group templates and change the __str__ method. Can you think of another solution? Which one do you think is the best? -
django-crontab works manually but not automatically
I hope i could get some help I have installed the django-crontab and created a cron task like the following inside of my cron.py inside my_django_app in django: import redis def hello(): redis.set("hello", "world") the above code works perfectly when I run python manage.py crontab run (cron hash)* and the key set successfully inside redis but the task doesn't run automatically have you had any similar experience? Note: I am using linux and python version 3.9 and django 3.2.3 -
NameError: name 'p' is not defined Python(Django)
I want to put the parameters from the database into a formula and it shows me an error like this. I want to solve it without global variables. Is this possible? How can I combine a parameter entered in the above function into the following function? BOT.PY ... ...; float_pattern = r'^\d{1,7}\.\d{1,2}$' ... ... def p_first(message): if message.text.isdigit() or re.match(float_pattern, message.text): chat_id = message.chat.id uid, _ = Profile.objects.get_or_create( external_id=message.chat.id, defaults={ 'name': message.chat.username } ) Message( profile=uid, param1=message.text ).save() p = Message.param1 print('Parameter (p) from:', chat_id) bot.send_message(message.chat.id, "Ajoyib, perimetr qabul qilindi!") msg = bot.send_message(message.chat.id, "<b>2. "Now secondside: "</b>", parse_mode="html") bot.register_next_step_handler(msg, height) return p else: msg = bot.send_message(message.chat.id, "Nice!") bot.register_next_step_handler(msg, p_first) def height(message): if message.text.isdigit() or re.match(float_pattern, message.text): chat_id = message.chat.id uid, _ = Profile.objects.get_or_create( external_id=message.chat.id, defaults={ 'name': message.chat.username } ) Message( profile=uid, param2=message.text ).save() h = Message.param2 print('Parameter (h) from:', chat_id) bot.send_message(message.chat.id, "Nice!" +f'{eval(str(p * h))} + ' is answer' else: msg = bot.send_message(message.chat.id, "Only number") bot.register_next_step_handler(msg, height) As a result: :( NameError: name 'p' is not defined MODELS.PY from django.db import models class Profile(models.Model): external_id = models.PositiveIntegerField( verbose_name='User ID', unique=True, ) name = models.TextField( verbose_name='User name', null=True, ) def str(self): return f'ID: {self.external_id} | Username: {self.name}' class Meta: verbose_name = … -
Moving object id parameter to consumers.py Django-Channels
I have a problem. The point is that I am making application with Django backend and React frontend. I wanted to make a websocket which allows to write in live-chat rooms. The problem is that I have no idea how to load dynamic a Room id. Ill try to explain. The point is that connect method from ChatConsumer class will load messages realted to room and send it by json to frontend. Ths is how it looks. class ChatConsumer(WebsocketConsumer): def connect(self): self.room_group_name = 'test' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) messages = Message.objects.filter(room=[HERE I NEED TO PUT ID OF ROOM]) data_ready_for_json =list( messages.values('room','body','user')) self.accept() self.send(text_data=json.dumps({ 'type':'chat', 'message': data_ready_for_json })) Iam trying to send this id from my views, where I have RoomRetrieveView built by generics.RetrieveAPIView. Here it is: class RoomRetrieveView(generics.RetrieveAPIView): queryset = Room.objects.all() permission_classes = (AllowAny,) serializer_class = RoomSerializer def get_serializer_context(self): context = super(RoomRetrieveView,self).get_serializer_context() context.update({'id' : self.get_object().id}) roomId = context['id'] return roomId I was trying to move this roomId variable from get_serializer_context to my consumers.py file but it wants me to put "self" attribute but I have no idea how to figure it out. I also tried to use get_object method but it also not working. I have no idea. I also … -
There is a way to manipulate queryset from model after fetching from data base?
I’m a new in Python Django and I’m trying to encrypt and decrypt specific data before inserting to database and after fetching. My motivation is to do this blind, Meaning that I want to do that automatically. My tables include foreign key. class person(BaseModel): bank_account = models.ForeignKey(BankAccount) For insert to database i override save method in BaseModel: class BaseModel(Model): def save(self, *args, **kwargs): if self.__name__ is "BankAccount": encrypt_model(self, encrypt) # save the model super(BaseModel, self).save(*args, **kwargs) and this is work fine. this save method call for each model inside the Person Model, i mean that if inside BankAcount model there is another Model with ForeignKey and this model should be also encrypted and i save Person model "save" method will call for each model inside so i can check if this modle should be encrypted. my problem is in the fetching data from data base, i tried to create Manager and override get_queryset method: class newManager(PolymorphicManager): def get_queryset(self): queryset = super().get_queryset() if self.__name__ is "BankAccount": decrypt_data(queryset) return queryset the problem with this approach is that this method "get_queryset" called only one time for model, for example: Peson.newManager.filter(id=6) get_queryset called only one time and self.__name__ not equal to BankAcount. i can … -
Force django page refresh coming from a react page
I impleted a "complex" form using django (which is one of the reasons why I couldn't do it with react, see thereafter). To access it the user first has to go through an index page written with react (to explain the purpose of the form filling). To go from the react to the django page I have the following button: <NavBtnLink to="/form_app/">Take the survey</NavBtnLink> with: import { Link as LinkR } from 'react-router-dom' export const NavBtnLink = styled(LinkR)` border-radius: 50px; background: #06beb6; ... ` So when I click on the button it redirect to the proper address. The problem is that the page remains blank. For the form to display, I need to refresh manually the page (using F5 or by cliking). I red different topics about similar issues but None of the solutions I found worked (eg: location.reload(true); or setting a dummy component={DummyComponent} in NavBtnLink...). Also all the topics were refering to the same issue from one plain react page to another (and not to a plain django page as mine). Would you have any ideas of what I could try as I am running out of idea. I just want a button on my react page to redirect … -
Visual Studio Code - Python Interpreter path does not work for me
as i already tried for hours by myself, i could not find out, what i am doing wrong. I am doing the Tutorial of Django on Youtube, which can be found on the following URL: https://www.youtube.com/watch?v=rHux0gMZ3Eg After craeting a virtual environment and starting a project in Virtual Studio Code, he tries to add the python path into the VSCode. In the video he is then able to use Python from the terminal inside the VSCode. However, around minute 19 you can find that in the video. If i do it by myself, nothing is happenning and i am also not able to use Python on the VSCode then. I did not figure out, what i am doing wrong, since i am exactly doing it like in the video. Does anyone have an idea, what i am doing wrong here? Thanks to anyone having an idea. Here are screenshots of what i have done for adding the path. enter image description here enter image description here enter image description here -
NOT NULL constraint failed: products_product.vendor_id django
so i recently changed my project user form to abstract base user and well my users can not add products or view their profile i know its problem in views.py and forms.py but whatever i change it too still has some probelm beside the error views.py rom django.urls import reverse_lazy from django.views import generic from django.contrib.auth.forms import UserChangeForm from django.utils.text import slugify from django.shortcuts import render, redirect from .models import NewUser from products.models import Product from .forms import ProductForm from .forms import UserCreationForm # Create your views here. def become_vendor(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) vendor = NewUser.objects.create(user_name=user.first_name) return redirect('home') else: form = UserCreationForm() return render(request, 'vendor/become_vendor.html', {'form': form}) @login_required def vendor_admin(request): context = { 'user':request.user } vendor = request.user.user_name return render(request,'vendor/vendor_admin.html',{'vendor': vendor ,'context':context}) @login_required def add_house(request): if request.method == 'POST': form = ProductForm (request.POST, request.FILES) if form.is_valid(): product = form.save(commit=False) NewUser.user_name = request.user.user_name product.slug = slugify(product.عنوان) product.save() return redirect('vendor_admin') else: form = ProductForm() return render(request,'vendor/add_house.html',{'form': form}) class UserEditView(generic.UpdateView): models = NewUser form_class = UserChangeForm template_name = 'vendor/edit_profile.html' seccess_url = reverse_lazy('vendor_admin') def get_object(self): return self.request.user forms.py rom django.forms import ModelForm from products.models import Product from django import forms from django.contrib.auth.models import … -
Django: why does my custom filter not find an existing item in the array?
I am a beginner in Django. Right now i am working on my first project: reservation of sits for cinema event. The html map of sits is based on the array of cols and rows, provided from the Hall model. There is also an Invoice model, which stores the information about reserved places, based on this event. Based on this, i am trying to disable the html-map checkboxes of the sit places, which are already reserved. Here is my code: views.py def event_map(request, slug, event_id): selected_event = Event.objects.get(pk=event_id) movie = selected_event.film hall = selected_event.hall time = selected_event.get_time_slot_display() date_event = selected_event.get_week_day_display() sits = list(range(0, hall.hall_sits)) cols = list(range(0, hall.hall_cols)) hall_information = generate_hall_information(hall.hall_name) reserved_places = list() invoices = Invoice.objects.all().filter(event=selected_event) for invoice in invoices: reserved_places += invoice.invoice_details.split(',') reservation_form = Reservation() if request.method == 'POST': print(request.POST) form = Reservation(request.POST) if form.is_valid(): post = form.save(commit=False) post.invoice = request.user post.event = selected_event post.save() return render(request, 'pages/event_map.html', { 'movie_name': movie.name, 'hall': hall, 'time': time, 'date': date_event, 'sits': sits, 'cols': cols, 'hall_information': hall_information, 'reservation_form': reservation_form, 'reserved_places': reserved_places, 'test': reserved_places }) event-map.html <div class="theatre-map event-map-grid hall-{{ hall }}" id="theatre-map-target"> {% for sit in sits %} {% if sit|if_in_list:reserved_places %} <label class="res" id="{{ sit }}" disabled=""></label> {% else %} <label … -
Django - My list coming from a form collapses to a string when i call it
when i print the full request body its a list but when i reference it turns into a string with just the first value in the list def create_quiz_post(request): if request.method == 'POST': quiz = Quiz.objects.create(name=request.POST['name'], creator=request.user) Quiz.objects.get(id=quiz.id).topic.add(request.POST['topic_id']) print(request.POST) print(request.POST['question']) return redirect('/') OUTPUT 1 <QueryDict: {'name': ['2'], 'question': ['2', '2'], 'option1': ['', ''], 'option2': ['', ''], 'option3': ['', ''], 'option4': ['', ''], 'topic_id': ['1']}> OUTPUT 2 2 -
Celery in docker container first works for a while, then starts to timeout
Deploying the project, everything works. After an indefinite time, celery stops responding. Getting a gunicorn error: sys.exit(1) Tried run task.deploy() inside the django container and nothing happens in the celery container. There are no errors in the logs either in django container or in celery container. If I restart the Celery container, then everything works again for a while, then it starts timeout again. Docker containers: - django - celery - celerybeat django settings celery settings: CELERY_BROKER_URL = REDIS_URL CELERY_RESULT_BACKEND = 'db+sqlite:///results.sqlite' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery.py in django project: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'YoungAI.settings') app = celery.Celery('YoungAI') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() docker-compose: version: '3' services: redis: container_name: redis image: redis:4.0.2 restart: always networks: - youngai youngai-nginx: container_name: youngai-nginx image: youngai-nginx build: conf/nginx/ restart: always networks: - youngai - third_party_backend youngai-backend: container_name: youngai-backend image: $CONTAINER_BUILD_IMAGE restart: always env_file: /opt/.env-youngai build: . command: ./docker-entrypoint.sh volumes: networks: - youngai - third_party_backend youngai-celery: container_name: youngai-celery image: $CONTAINER_BUILD_IMAGE restart: always … -
Django - Href not redirecting user but being loaded locally
I am creating a simple application in django. I have an element, and when the user clicks on it, I want to be able to redirect them to a new page (classes.html). I used href="{% url 'classes' %}", but when the user clicks on it, nothing happens. However, I can see that the url has been loaded because the tag at the bottom screen loads the URL. Additionally, when I go to inspect the , I see that the URL has been loaded and when I click on it, it takes me to the classes URL. Can someone please help me so that when the user clicks on the , it redirects them to the classes screen? I have tried conducting a hard reload, re doing my URLS and views, and setting up a virtual enviorment, but nothing seems to work. -
django How do I solve a: NOT NULL constraint failed: accounts_user.group error?
Hi all I'm struggling to diagnose this error. I have looked through similar questions, however their's seem to be specific to ID's names etc. Im trying to create a new user when they fill out a register form. However when the form is submitted I get the following: " NOT NULL constraint failed: accounts_user.group " My code and the exact error i get is below, any help will be appreciated Form.py from django import forms from django.contrib.auth import get_user_model, authenticate, login from .models import EmailActivation, GuestEmail, User User = get_user_model() class RegisterForm(forms.ModelForm): """ A form for creating new users. Includes all the required fields, plus a repeated password. """ password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('full_name','email',) 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") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(RegisterForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) user.is_active = False # send confirmation email via signals if commit: user.save() return user Models.py from django.conf import settings from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) from django.db … -
Django profile not being updated
Enabling my users to update their profile information. However, when I send new profile information, Django sends my back the profile information I had prior to updating. Simply put I would to receive updated profile information when I update a user profile along with a new access_token (I use the information to populate my profile). This is my serializers.py: class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) class Meta: model = User #, 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name'] extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}} def validate_email(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) return value def validate_username(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(username=value).exists(): raise serializers.ValidationError({"username": "This username is already in use."}) return value def update(self, instance, validated_data): user = self.context['request'].user if user.pk != instance.pk: raise serializers.ValidationError({"authorize": "You don't have permission for this user."}) instance.first_name = validated_data['first_name'] instance.last_name = validated_data['last_name'] instance.email = validated_data['email'] instance.username = validated_data['username'] instance.save() return instance urls.py: path('update_profile/<int:pk>', views.UpdateProfileView.as_view(), name='update_profile'), and my views.py: class UpdateProfileView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UpdateUserSerializer @action(detail=True, methods=['PUT']) def perform_update(self, serializer, pk=None): serializer.save(user=self.request.user.id) -
PAGINATION using class APIView in Django Rest Framework
I have try to paginate my data.. but this is not work , I'm still getting all data from DataBase this is views.py : class User_apiView(APIView): pagination_class=PageNumberPagination def get(self, request): user = User.objects.all() # pagination_class=PageNumberPagination serializer = TripSerializer(user, many = True) return Response(serializer.data) this is settings.py : REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 2, } this the data I recieve in this url http://127.0.0.1:8000/api/users/?PAGE=4&PAGE_SIZE=1 HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 115, "is_normaluser": null, "is_agency": null, "last_login": "2022-02-11T20:28:13.506519Z", "is_superuser": true, "first_name": "qaz", }, { "id": 115, "is_normaluser": null, "is_agency": null, "last_login": "2022-02-11T20:28:13.506519Z", "is_superuser": true, "first_name": "qaz", }, { "id": 115, "is_normaluser": null, "is_agency": null, "last_login": "2022-02-11T20:28:13.506519Z", "is_superuser": true, "first_name": "qaz", }, ] -
How i can ouput categiries in django on dpopdown in navbar?
Views, functions from categories def get_categories(request, cat_id): product = Product.objects.filter(cat_id=cat_id) cats = Category.objects.all() if len(product) == 0: raise Http404() context = { 'product': product, 'cats': cats, 'menu': menu, 'title': 'Отображение по категориям', 'cat_selected': cat_id, } return render(request, 'task1/get_category.html', context=context) Models with get_absolute_url class Category(models.Model): name = models.CharField(max_length=255, verbose_name='Категории') slug = models.SlugField(max_length=255, unique=True, verbose_name='URL', db_index=True) class Meta: verbose_name = 'Категории' verbose_name_plural = 'Категории' def __str__(self): return self.name def get_absolute_url(self): return reverse('сategory', kwargs={'cat_id': self.pk}) Urls.py path('category/', get_categories, name='category'), This is piece of code from base.html. Dpodown from navbar. <div class="collapse navbar-collapse" id="navbarNavDarkDropdown"> {% for c in cats %} <ul class="navbar-nav"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDarkDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Категории </a> <ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownMenuLink"> <li><a class="dropdown-item" href="#">{{ c.name }}</a></li> {% else %} <li><a class="dropdown-item" href="#">{{ c.name }}</a></li> </ul> {% endif %} </li> </ul> {% endfor %} </div> I'm really idk what to do, help me please I've tried, but i get mistake Navbar looks like, i have 4 categories and i get 4 columns in navbar -
How to make Whitelisted IPs won't be blocked and other IPs should be blocked if crosses the certain time in django rate limited?
@method_decorator(ratelimit(key='ip', rate='10/m', block=True), name="process_request") Class SomeMiddleware (object): def process_request(request): Pass I have ALLOWED_IPS = ["SOME IP"] in settings.py and i imported here. If any IPs matching with this list, they won't be blocked under this condition otherwise it does. How can I achieve this? -
Get username of authenticated user in middleware [Djoser] Django
Im using django with rest framework and djoser. I have a code to check the latest activity on the website. But i have problem to get username of authenticated user. request.user.is_authenticated always return false. On frontend i have vue. p.s When i login to admin panel of 127.0.0.1:8000 show "true" from django.utils import timezone from .models import CustomUser class UpdateLastActivityMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request, 'user') print(CustomUser.objects.filter(is_online=True)) print(request.user.is_authenticated) if request.user.is_authenticated: CustomUser.objects.filter(user__id=request.user.id) \ .update(last_online_at=timezone.now()) -
django-social-auth redirect to different url based on params
I am using social-auth-app-django to enable OAuth2 from google. My application has two types of users and both are given an option to use google auth. Now after these users register using google, I want to redirect to some page where they add additional information based on the type of user. I am not able to figure out a way how to identify them based on the type of user. I am looking for a way where I can send extra parameter to google and then google return that parameter. This way I can identify the user type. I am simply providing the following in django template. <a href="{% url "social:begin" "google-oauth2" %}"><button>Google</button></a> Edit: One way I am thinking is of having two redirect URL configured in google. Then I can simply add function for these two redirect URL and my problem will be solved. I am not able to figure out how to add that redirect URL in the request to google. -
"Cannot call delete() after .distinct()" error after django update
I am using djangocms_blog. Today I updated django from 3.1 to 3.2.12 and suddenly when I try to delete post object, there is "Cannot call delete() after .distinct()" error Traceback: env\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … env\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … env\lib\site-packages\django\contrib\admin\options.py, line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) … env\lib\site-packages\django\utils\decorators.py, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) … env\lib\site-packages\django\views\decorators\cache.py, line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) … env\lib\site-packages\django\contrib\admin\sites.py, line 232, in inner return view(request, *args, **kwargs) … env\lib\site-packages\django\utils\decorators.py, line 43, in _wrapper return bound_method(*args, **kwargs) … env\lib\site-packages\django\utils\decorators.py, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) … env\lib\site-packages\django\contrib\admin\options.py, line 1739, in changelist_view response = self.response_action(request, queryset=cl.get_queryset(request)) … env\lib\site-packages\django\contrib\admin\options.py, line 1408, in response_action response = func(self, request, queryset) … env\lib\site-packages\django\contrib\admin\actions.py, line 45, in delete_selected modeladmin.delete_queryset(request, queryset) … env\lib\site-packages\django\contrib\admin\options.py, line 1109, in delete_queryset queryset.delete() … env\lib\site-packages\django\db\models\query.py, line 728, in delete raise TypeError('Cannot call delete() after .distinct().') … I restored Django 3.1 version and everything works fine, but working on old version isn't best solution -
How to make Django username field of LoginView(FormView) lowercase?
I've made it so that any user that signs up with a username will automatically have their username converted to lowercase. user/forms.py I now have the issue where I can't figure a way to convert the username in the login form to become lower when submitted. As I would still like the user to be able to enter their name in the case of their choice. I've tried the python tolower() function on a few things in the LoginView, yet unsuccessful. If anyone has an idea on how I could achieve this please let me know. Here is the user/forms.py class UserSignupForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email", "password1", "password2"] def clean_username(self): username = self.cleaned_data["username"].lower() if not re.match(r"^[A-Za-z0-9_]+$", username): raise forms.ValidationError( "Sorry , you can only have alphanumeric, _ or - in username" ) else: return username Here is the user/urls.py path("signup/", user_view.signup, name="signup"), path("login/",auth_view.LoginView.as_view(template_name="user/login.html"),name="login"), -
Form action is not calling the required function from views.py in Django
I am new in Django and doing my first project in it. I had made a form in my index.html file and that form took an image, and sent it to a predictImage function in views.py file. The predictImage function applied YOLO model on the image and returned the image with labels to the same index.html page. This was working fine and I was getting the required results. After the submit button was clicked, I was getting redirected to index.html/predictImage where the results were being shown. (I had conditions added in my index.html to show the results) Then, I decided to add a Users Model and made a Login page for me, user was required to login before he could upload the image. For this, I added sessions as well. Now, I created a Photo model, to store every photo that every user uploads. All of this was successfully made but now, when I tried to do the same thing again, i.e., upload the image and submit it, it didn't work and it instead redirected me to index.html I tried to debug this, and I found out that I was not even going to views.predictImage when I clicked the submit … -
What is the easiest way to create a histogram (with target line) in Chart.js?
I have a matplotlib code that seems to do what I want it to do. I am trying to use it in a django web app. For example: home_totals_dict[a] = [ 140, 130, 120, ...] a = team_name plt.figure() plt.hist(x=home_totals_dict[a], bins='auto', color='#0504aa',alpha=0.7, rwidth=0.5) plt.hist(x=away_totals_dict[b], bins='auto', color='#d62728',alpha=0.7, rwidth=0.5) plt.axvline(x = c, color = "k",linestyle = "--" ) plt.xlabel(a + "/ "+ b) The result is the image attached. Every time I try do something similar in chart.js the x axis gets all messed up and am having trouble normalizing the x-axis prior to adding the data to chart.js -
Serializer returns media files URLs in http not in https in Django Rest Framework
I'm trying to serialize a model and one of its fields is a FileField when calling serialiser.data it returns the URL of the FileField in an HTTP schema, not an HTTPS. I get { "id": 1, "name": "demo", "file": "http://domain-name.com/media/image.png" } I want it to be { "id": 1, "name": "demo", "file": "https://domain-name.com/media/image.png" } I'm using Nginx and set proxy_set_header X-Forwarded-Proto https; Then in your Django settings added the following: USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') And the problem is not fixed, what should I do to solve it? -
send_mail (smtp) from docker-compose (django + nginx + gunicorn)
I am trying to send email via Django. The mail should be sent to the user who would register to our system using Gmail. I am also using docker-compse django, nginx, gunicorn and postgres. This is my email configurations inside the django. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_USE_TLS = True EMAIL_HOST_USER = get_secret("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = get_secret("EMAIL_HOST_PASSWORD") DEFAULT_FROM_EMAIL = EMAIL_HOST_USER and docker-compose version: '3.7' services: web: build: context: ./dj-psych dockerfile: Dockerfile.prod command: gunicorn config.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/static/ - media_volume:/home/app/web/media/ expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:13.0 volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - static_volume:/home/app/static - media_volume:/home/app/static ports: - server-port:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: nginx.conf upstream config { server web:8000; } server { listen 80; location / { proxy_pass http://config; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/static/; } location /media/ { alias /home/app/media/; } } I think the smtp server port (586) should be open in docker. So I tried binding port web and nginx. But I can't. how can i do it?? I tried. from django.core.mail import EmailMessage email = EmailMessage('subject', 'body', to=['yj.jeon.gn@gmail.com']) email.send() This is …