Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HTTP_HOST Stripping via Firewalls and VPNs
I have an issue that's presenting as a CORS-related issue from a frontend (React) making API calls to a backend (Django). However, looking at the logs, I'm seeing things like this: django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: '123.456.789.101:8007'. You may need to add '123.456.789.101' to ALLOWED_HOSTS. The site works fine from my PC, several friends, and mobile devices, via my VPN, but fails to make API requests when behind certain firewalls (corporate) or via online VPN services that let one type in a website, visit it via an in-browser window (not naming names b/c that's beside the point here). What seems to be the issue is a security measure whereby the firewalls are stripping out the HTTP_HOST specified by the site and adding in the actual IP to avoid e.g. HTTP_HOST-based spoofing. Is there any way(s) to address this that doesn't involve assigning a static IP to my host and hard-coding that into the ALLOWED_HOSTS? For example, I like testing new apps on easy 1-click deploy type services like Digital Ocean, Railway, Netlify, etc. that are great but don't always provide the option for a static IP (not focusing on a specific service here). Am I stuck hoping my PaaS provider exposes … -
Having trouble with PUT request in React with Django backend: the Props can update State in DevTools but the State doesn't update the Props
I've probably made a stupid error I'm brand new at React; I'm building a POC for a class assignment and need to demonstrate a GET and PUT request in react on existing data in a django backend. The GET method works, and the API works. It's all very simple code, so I don't know where I went wrong: import React, { Component } from 'react' import './App.css'; import axios from 'axios' import Temperature from "./components/Temperature" import BootstrapSwitchButton from 'bootstrap-switch-button-react' class App extends Component { constructor(props) { super(props); this.state= { deviceEnabled: false, viewActivated: true, deviceList: [] }; } componentDidMount() { this.refreshList(); } refreshList = () => { axios .get("http://localhost:8000/api/devices/") .then(res => this.setState({ deviceList: res.data })) .catch(err => console.log(err)) }; handleSubmit = device => { if (device.id) { axios .put(`http://localhost:8000/api/tasks/${device.id}/`, device) .then(res => this.refreshList()) } axios .post("http://localhost:8000/api/devices/", device) .then(res => this.refreshList() ) } // Checks if device is activated or not displayActivated = status => { if (status) { return this.setState({ viewActivated: true }) } return this.setState({ viewActivated: false }) } displayEnabled = status => { if (status) { return !this.state.deviceEnabled; } return this.state.deviceEnabled; } // Renders activated and inactive devices under proper heading renderDeviceList = () => { return ( <div … -
index our of range in django template
I'm beginner in django and i'm trying to create a website and in its blog page there is a section that shows prev post and next post. I gave them the url of posts using a for loop that gives the id of posts from data base but in the first post it gives me the "index out of range" error here is the views.py and that section of blog template: views.py: def blog_single(request, pid): posts = get_object_or_404(Post, id=pid, status=1) ls = list(Post.objects.filter(status=1)) lis = [] for i in ls: lis.append(i.id) indpid = lis.index(pid) index_prev_post = indpid + 1 id_prev_post = lis[index_prev_post] index_next_post = indpid - 1 id_next_post = lis[index_next_post] name_prev_querry = Post.objects.filter(id=id_prev_post) name_prev_list = list(name_prev_querry) name_prev = name_prev_list[0].title name_next_querry = Post.objects.filter(id=id_next_post) name_next_list = list(name_next_querry) name_next = name_next_list[0].title context = {'post':posts, 'prev':id_prev_post, 'next':id_next_post, 'name_prev':name_prev, 'name_next':name_next} return render(request, 'blog/blog-single.html', context) template: </div> <div class="navigation-area"> <div class="row"> <div class="col-lg-6 col-md-6 col-12 nav-left flex-row d-flex justify-content-start align-items-center"> <div class="thumb"> <a href="#"><img class="img-fluid" src="{% static 'img/blog/prev.jpg' %}" alt="" /></a> </div> <div class="arrow"> <a href="#"><span class="lnr text-white lnr-arrow-left"></span></a> </div> <div class="detials"> <p>Prev Post</p> <a href="{% url 'blog:single' pid=prev %}"><h4>{{name_prev}}</h4></a> can you please tell me what's wrong with my code? I have tried changing the name_prev … -
Should I inherit from User model
I have two other models that should have all the functionalities that User model have. That's why in those two models, I am inheriting from User model. default_role = "admin" class User(AbstractBaseUser): ... image = models.ImageField(upload_to=user_directory_path, blank=True, null=True) role = models.CharField(max_length=20, choices=ROLE_CHOICE, default=default_role) .... class Student(User): ... some_fields_related_to_student ... def save(): self.role = "student" class Teacher(User): ... some_fields_related_to_teacher ... def save(): self.role = "teacher" def user_directory_path(instance, filename, role): extension = filename.split('.')[-1] return f"{role}/{instance.id}.{extension}" When I try to put the image pictures for Teacher and Student models, I want to put them in: ".../teachers/{teacher.id}.{extension}" ".../students/{student.id}.{extension}" these folders. How I can pass the role field to user_directory_path function? Also, my another question is that should I inherit from User at all? Whenever I create Student or Teacher it is also creating that model in User too, but for me it looks like not optimal, since we are kinda duplicating the information -
VSCode DJLint extension formats python files
My DJLint extension for VSCode recognizes problems in python files however it is not supposed to. It is supposed to run only in html files. DJLint error in python File Now my settings tell me that this extension is only running in the default file formats that do not include .py as seen here. What am I missing? -
Why aren't my serializer method fields being called?
I have the following django model: class HelpItem(TimeStampMixin): user = models.ForeignKey(User, related_name='help_items', on_delete=models.DO_NOTHING) description = models.TextField() support_choice = models.PositiveSmallIntegerField( choices=SubscriptionPlan.SUPPORT_CHOICES, default=SubscriptionPlan.EMAIL ) parent_entity = models.ForeignKey(ParentEntity, related_name='help_items', on_delete=models.DO_NOTHING, null=True) Im sending a post request to create a HelpItem through this view: class HelpItemView(CreateAPIView): permission_classes = (IsAuthenticated, ) serializer_class = HelpItemSerializer def post(self, request, *args, **kwargs): help_item = self.serializer_class(data=request.data, context={ 'user': request.user, 'selected_parent_entity': request.selected_parent_entity }) help_item.is_valid(raise_exception=True) help_item = help_item.save() return Response(self.serializer_class(help_item).data, status=status.HTTP_201_CREATED) And this is my serializer: class HelpItemSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() parent_entity = serializers.SerializerMethodField() support_choice = serializers.SerializerMethodField() class Meta: model = HelpItem fields = ['description', 'support_choice', 'parent_entity', 'user'] def get_user(self, obj): return self.context['user'].id def get_parent_entity(self, obj): return get_parent_entity_for_configurations(obj.user, self.context['selected_parent_entity']) def get_support_choice(self, obj): try: return Subscription.objects.get(parent_entity=obj.parent_entity).subscription_plan.support except Subscription.DoesNotExist: print('No subscription exists.') Shouldn't the method fields be called before the serializer tries to save the HelpItem object? I get the following error: null value in column "user_id" of relation "smartsign_helpitem" violates not-null constraint DETAIL: Failing row contains (22, 2023-10-27 14:57:23.696476+00, 2023-10-27 14:57:23.696497+00, need help, null, null, 1). So basically the description is accessed but support choice sets to default value (1) and the user and parent entity columns are null. Why? -
Django Updatign Fields in views.py not working
I have a Django Application for clients home data, I want to Change the password of user and editing other fields, I can change all the data in my console but when I use views.py and forms, the data does not save without any errors. I paste my codes here, please help me :) views function: `@login_required def profile_home(request): user = request.user home = Home.objects.filter(user=user).first() if request.method == 'POST': if request.POST.get('password2'): form_change = ChangePasswordForm(request.POST) if form_change.is_valid(): data = form_change.cleaned_data user.set_password(data['password2']) user.save() else: form_edit = HomeEditForm(request.POST) if form_edit.is_valid(): data = form_edit.cleaned_data user.first_name = data['first_name'] user.last_name = data['last_name'] user.email = data['email'] home.national_code = data['national_code'] home.mobile = data['mobile'] home.province = data['province'] home.city = data['city'] home.address = data['address'] home.zip_code = data['zip_code'] user.save() home.save() messages.success(request, 'با موفقیت ذخیره شد', 'success') form_edit = HomeEditForm( initial={'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email, 'national_code': home.national_code, 'mobile': home.mobile, 'province': home.province, 'city': home.city, 'address': home.address, 'zip_code': home.zip_code}) form_change = ChangePasswordForm() return render(request, 'panel/profile_home.html', context={'home': home, 'form_edit': form_edit, 'form_change': form_change})` The Model: `class Home(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='User') national_code = models.CharField(max_length=10, verbose_name='National Code') mobile = models.CharField(max_length=13, verbose_name='Mobile', validators=[MinLengthValidator(11)]) province = models.CharField(max_length=20, verbose_name='Province') city = models.CharField(max_length=50, verbose_name='City') address = models.TextField(verbose_name='Address') zip_code = models.CharField(max_length=10, verbose_name='Zip Code', validators=[MinLengthValidator(10)]) score = models.IntegerField(verbose_name='Score', default=0, validators=[MinValueValidator(0), MaxValueValidator(20000)]) … -
Unresolved attribute reference 'objects' for class '_ _'- in pycharm
Project information i was work with a small project name - Web_applications. where i simply make a django website project I was making a website that take a topics & And write about for that topics } What error i was encountering in my** pycharm ide** i was encountering error in my pycharm terminal error - { Unresolved attribute reference 'objects' for class 'Topic' }. When i was adding a function - Topic section in my view.py file. **code ** def topics(request): """Show all the topics""" all_topics = Topic.objects.order_by('date_added') context = {'topics': all_topics} return render(request, 'Web_applications_apps/topics.html', context) -where the error happen In this objects attribute section , was highlighted in yellow color and show error in terminal. error - Unresolved attribute reference 'objects' for class 'Topic' i was copy the code and error, ask with CHATGPT & BARD but they not able to give extact answer about this error 2.Then i search this error in stackoverflow and i get some over view why i was get this error -
django and react routing integration
I'm a python Django newbie, and I'm coding for a React Django app. My question is about routing or integration of Django and React, until now I have made a view for Django to send React app (index.html) to client and set the URL for it on home page "www.domain.com/". Client can get app in that URL and app works, but there is a problem client can just get app from home page and other URLs will show a 404 error, means client must first go to home page then go to other pages this can be lead to a problem. For example if client when it don't have the app, and then directly type a URL that is for inside of react routing it says error 404 , so Django dont send the app , do I need to put view for every page of React app ? Because i dont think it must be like this i know Django and react routing are separate and React have its own routing because its a single page app (SPA). I have searched in GitHub projects and find a TemplateView in Django URLs do i need to fix the problem with … -
Django-filters how to use BooleanFilter to range or else
Good day, a question about "django-filters", "rest framework" How to make a filter to -1 option took up to 50% (in the decimal model), -2 option after 50%, -3 option equal 50 I did it with Boolean Filter and an additional "method" function - two fields, if true, then output the corresponding queryset. However, they are tied through one field and, accordingly, use one queryset, which makes them mutually exclusive when called at the same time, and not complementary as I need. I'm still looking at "ChoiceField", but I don't know if it's possible. p.s. I tried to unite use union method in functions but get error "ORDER BY not allowed in subqueries of compound statements." MY code from filter class: ` class ProductsFilter(filters.FilterSet): type_one = filters.BooleanFilter(field_name='percentage_field', method='filter_one') type_two = filters.BooleanFilter(field_name='percentage_field', method='filter_two') type_half = filters.BooleanFilter(field_name='percentage_field', method='filter_half') def filter_one(self, queryset, name, value): if value is True: return queryset.filter(percentage_field__range=(50.1, 100)) else: return queryset def filter_two(self, queryset, name, value): if value is True: return queryset.filter(percentage_field__range=(0, 49.9)) else: return queryset def filter_half(self, queryset, name, value): if value is True: asd = queryset return Product.objects.filter(percentage_field=50) else: return queryset class Meta: model = Product fields = ['name','price'] ``` Filtering by one and by several at once … -
Django translations of path **kwargs values in urls.py
How can I translate the values passed to **kwargs within the urls.py file in Django, based on the language selected by the user? Translations in templates are working, and the language is determined by the Accept-Language header set by the Nginx server. However, this language selection doesn't have any effect within the urls.py file, and instead is determined by LANGUAGE_CODE in settings.py file. Here is an example urls.py: from django.urls import path from main.views import IndexView from django.utils.translation import pgettext app_name = 'some_site' urlpatterns = [ path('', IndexView.as_view(), {'SITE_SEO_title': pgettext('home', 'SITE_SEO_title')} ] My question is, how can I translate the **kwargs values passed to the path method according to the user's selected language, and not according to LANGUAGE_CODE? Is there a different approach I could use to achieve this? -
How to connect django to an infomix database? [duplicate]
I want to connect my django project with an informix database without using ODBC. Is there any way to connect to my informix database throught my django application. what approuch should i follow i would be very greatfull if you could help me. -
Django Rest Framework Query Optimization
I need to remove these extra similar queries into database. Can you optimize this to remove similar queries: models.py: class Comment(BaseModel): description = models.TextField() article = models.ForeignKey( Article, on_delete=models.CASCADE, related_name="comments" ) author = models.ForeignKey( Author, on_delete=models.CASCADE, related_name="comments" ) reply_to = models.ForeignKey( "self", on_delete=models.CASCADE, related_name="replies", null=True ) serializers.py: class CommentSerializer(serializers.ModelSerializer): replies = serializers.SerializerMethodField(read_only=True) class Meta: model = Comment fields = ["id", "description", "author", "replies"] def get_replies(self, comment): return CommentSerializer(comment.replies, many=True).data views.py: class ArticleViewSet(ModelViewSet): queryset = ( Article.objects.select_related("category").prefetch_related("images").all() ) serializer_class = ArticleSerializer pagination_class = DefaultLimitOffsetPagination permission_classes = [IsAdminOrReadOnly] @action(detail=True, permission_classes=[IsAuthenticated], serializer_class=CommentSerializer) def comments(self, request, *args, **kwargs): self.queryset = ( Comment.objects.filter(article_id=self.kwargs["pk"], reply_to=None) .prefetch_related("replies") .all() ) return self.list(request, *args, **kwargs) I need to remove these extra similar queries into database. -
Converting Date to "1434758400000" with pd.datetime in Django
I'm working on a Django project, and I've encountered an issue when using the pd.datetime function. When I try to convert a date using pd.datetime, it's returning a value like "1434758400000" instead of a proper datetime object. I'm puzzled by this behavior and unsure of what could be causing it. Here's a code snippet that illustrates the problem: # Convert the 'date' column to a datetime object df['date'] = pd.to_datetime(df['date']) # Create a DataFrame to represent all unique date-district combinations unique_dates = pd.date_range(start=df['date'].min(), end=df['date'].max()) unique_districts = df['pdistrict'].unique() date_district_combinations = pd.MultiIndex.from_product([unique_dates, unique_districts], names=['date', 'pdistrict']) full_df = pd.DataFrame(index=date_district_combinations).reset_index() # Merge this new DataFrame with your original data to fill in missing combinations filled_df = full_df.merge(df, on=['date', 'pdistrict'], how='left') # Fill missing 'cases' with 0 or cumulative sum filled_df['cases'].fillna(0, inplace=True) The output of this code is something like: "1434758400000". I would expect the output to be a valid datetime object, but this unexpected behavior is causing issues in my project. Has anyone encountered this before or can provide insights into what might be going wrong? I've checked my code and the input date format, and they seem correct. Could there be any configuration settings in Django or Pandas that could cause this issue? … -
Password authentication failed while running taiga on localhost through source code
I am trying to configure taiga on localhost with source code .At start while creating taiga database i had put password which is same as django password and as well as machine paasword . Still it shows password authentication failed for user taiga . Given below is the command and after which it shows errro enter image description here command :- python manage.py migrate --noinput output :- taiga issue taiga issue 978×506 122 KB I have done some changes in pg_hba file Database administrative login by Unix domain socket local all postgres peer TYPE DATABASE USER ADDRESS METHOD “local” is for Unix domain socket connections only local all all md5 IPv4 local connections: host all all 127.0.0.1/32 scram-sha-256 IPv6 local connections: host all all ::1/128 scram-sha-256 Allow replication connections from localhost, by a user with the replication privilege. local replication all peer host replication all 127.0.0.1/32 scram-sha-256 host replication all ::1/128 scram-sha-256 local all taiga peer local all taiga md5 local all taiga peer host taiga taiga 127.0.0.1/32 md5 Here the password is same as the password of Taiga database user , postgres and django as well as machine. Below is the output when i try to access postgres with … -
Django-import-export. Export selected records only?
I'm using the great django-import-export addition. We standard have 2 options import and export. I would like to have an extra option to export selected records only. Would be a nice addition. How can I achieve this? I use the standard configuration in the Django admin. -
TypeError at / TodoListServices.list_todo_paginate() missing 1 required positional argument: 'page'
//Views class TodoList(APIView): def get(self,request,page=None, format=None): todos = [] if page is not None: todos = TodoListServices.list_todo_paginate(page) else: todos = TodoListServices.list_todo_paginate(1) serializer = TodoSerializer(todos, many=True, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) //Services class TodoListServices: @staticmethod def list_todo_paginate(page): page_number = page page_size = 10 if page_number is None: page_number = 1 todos = todo.objects.all()[ (page_number - 1) * page_size: page_number * page_size ] return todos I am getting a TypeError : missing 1 required positional argument how do I solve this ? -
Increase email sending limit SMTP Go daddy
I have a GoDaddy workspace email which I am using in Django project using smtp smtpout.secureserver.net port 587 the problem is when on new user creation in my Django project I sent out verification email and as soon as it sends 5 emails it reach limit and gives error "it has exceeded its 24-hour sending limit. Messages to 5 recipients out of 5 allowed have been sent. Relay quota will reset in 24 hours." -
Django project with qn informix database
I'm currently working on a django project that connects to my infomix database (using the 64-bit ODBC driver) and it works perfectly, the problem is that when I try to insert the data in Arabic language, it doesn't work and I get an odbc error. I tried using 32-bit ODBC and it worked as it should. I was wondering how to get 64-bit odbc to accept the encoding or features of other languages or can I use another approach to connect my project to infomix? as using 32-bit odbc is not an option. I hope you can help me and thank you in advance. Inserting data in aranic into my infomix database -
What is to best way in Django to replace emails with other notification solution?
I have a site with an increasing number of user (now about 500 active users). I need to send notifications to them several times a day and I see that the email notification is not the best way to notify them because they get lots of emails from others. I need to send personal informations like tasks, notifications about comments, etc. so I need to send DM's. I wonder if somebody has experience with chat solutions like Discord, Viber, Telegram, Discord, WhatsApp. I'm using Slack for some purposes but I don't want to add the users to a Slack channel to send DM's. I 'm sending about 3.000-5.000 notifications in a month. The budget is an important thing because I don't want to bill extra fees to the users for using a chat app and not email. Thank you in advance! -
Website not working without www in https domain
I have made a django chatting application that works when the URL is https://www.aniconnect.org but it does not work when it is just https://aniconnect.org I don't know why this is happening but I did some digging and it supposedly might be caused by my nginx configuration or something is wrong with letsencrypt, my SSL certificate provider. The following is my nginx configuration: server { listen 80; server_name www.aniconnect.org my.ip.address aniconnect.org; listen 443 ssl; ssl_certificate /etc/letsencrypt/live/www.aniconnect.org/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.aniconnect.org/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/gamedeveloper/anime_chat/anime_chat_app/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /ws/ { proxy_pass http://127.0.0.1:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; } } I followed the guide at https://certbot.eff.org/instructions?ws=nginx&os=ubuntufocal to get my ssl certificate for www.aniconnect.org which worked (also the reason why the site might be only visible at www.aniconnect.org) and I tried to activate my SSL certificate for aniconnect.org using certbot and this was the output: gamedeveloper@animechatapp:~$ sudo certbot --nginx Saving debug log to /var/log/letsencrypt/letsencrypt.log Which names would you like to activate HTTPS for? We recommend selecting either all domains, or all domains in a VirtualHost/server block. - - - - … -
RuntimeError: Failed to lock Pipfile.lock - while installing mysqlclient
when I try to install mysqlclient on my Django project, I am facing this error. since I am a complete beginner for python-jango, could someone help me out on solving this issue? -
How can do i use django to register a new user?
I’m fairly new to django. How can i use abstractBaseUser class to create a custom user (with basic email, password, username, etc) and create a function based view that handles the httpRequest after it was mapped from the urls in the app? I basically want to create a function based view that processes a specific POST request to create a new user and returns a response with the successful user creation announcement. I want to handle user login as well. Thank you in advance! I thought about just processing the Http request and validating the fields and then saving the new user object in the database if the user submitted valid information. -
Restrict Access to DRF subdomain on host
I have a main domain which is for my Vue.js that is domain.com and I also have a sub-domain for my DRF backend with the name of api.domain.com; I do not want that the api and urls in my backend to be accessible under the corresponded url; e.g if anyone enters the url of api.domain.com/companies my backend info and data are being shown there but I want to remove access for anyone to see all of the pages of the backend subdomain. How can I do that? -
How to delete row when use Django only templates
I tried several options but to no avail. How can I get the job done if I only use templates? I want to delete the selected record with a button. I also have an add button in the html, after the add button it shows me the base again. All entries come with a delete button, but I can't get the job done. urls.py: urlpatterns = [ path("", views.index, name='index'), path("all_flat", views.all_flat, name='all_flat'), path("contact", views.contact, name='contact'), path("about", views.about, name='about'), path("save", views.testing, name='save'), #path("save/<int:pk>", views.delete, name='delete'), ] views.py: @api_view(['GET', 'POST']) def testing(request): mydata = models.FlatModelSqlite.objects.all() serializer_class = serializers.FlatSerializerSqlite(mydata, many=True) if request.method == "GET": html_save = "MyHome/save.html" template = loader.get_template(html_save) context = { 'mymembers': serializer_class.data, 'flatP': ForecastField_all(), } return HttpResponse(template.render(context, request)) elif request.method == "POST": item_serializer = serializers.FlatSerializerSqlite(data=request.data) if item_serializer.is_valid(): item_serializer.save() return HttpResponseRedirect(redirect_to='save') else: er = item_serializer.errors html_save = "MyHome/save.html" template = loader.get_template(html_save) context = { 'mymembers': serializer_class.data, 'flatP': ForecastField_all(), 'errors': er, } return HttpResponse(template.render(context, request)) #@api_view(['GET', 'POST']) #def delete(request, pk): # if request.method == 'POST': # flat_delete = models.FlatModelSqlite.objects.get(pk=pk) # flat_delete.delete() # return HttpResponse(redirect_to='save') html /save: {% for x in mymembers %} <tr> <td>{{ x.id }}</td> <td>{{ x.Address_N }}</td> <td>{{ x.Project_N }}</td> <td>{{ x.Fasi }}</td> <td>{{ x.Status }}</td> <td> <form method="post"> …