Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't connect to django application running on AWS Ubuntu EC2
I am runnig my Django application on AWS EC2 t2.micro with Ubuntu. I've successfuly installed all modules, created a PostgreSQL database, and made all migrations. Now when I'm running python manage.py runserver 172.31.27.208:8000 I can't connect to it in browser, getting ERR_CONNECTION_TIMED_OUT error. python manage.py runserver 172.31.27.208:8000 returns: System check identified no issues (0 silenced). January 30, 2020 - 11:10:59 Django version 3.0.2, using settings 'project_test.settings' Starting development server at http://172.31.27.208:8000/ Quit the server with CONTROL-C. So I assume the server running properly. I am using private ip form ec2 console which, I've checked, is matching to the ip adress returning by running command ifconfig. TCP port is opened in AWS security_group inbound rules on port 8000. I've also checked netstat -lan after running django server, it shows: tcp 0 0 172.31.27.208:8000 0.0.0.0:* LISTEN I have been looking for same issues and everything listed in them seems to be correct in my case. Since that I have no idea what is going wrong. Can provide more information if you need something. Will appriciate any help. Thank you. -
How do I set up staging and production apps in Heroku, using Docker containers?
I'm trying to set up staging and production apps in Heroku. Nothing fancy, just a way to test the app is running okay on Heroku's platform before it gets pushed to production. The project is built using the Django web framework, and the project is containerised in Docker. I've tried setting up a pipeline in Heroku, but when I click "promote to production" on the staging app, it comes up with an error that it's not supported for docker containers. If that's true (and Docker is still popular), what is a recommended workflow for this? The only workaround I can think of is to simply have two apps running in Heroku (project-name-staging and project-name-production) and just push the codebase to one and then the other manually. But surely there's a better way. Thanks in advance for your help. -
How to retrieve a many-to-many field with backward relationships lookup in Django REST Framework serializer?
Please correct my title if it's not correct. My problem is I want to retrieve FinishType's name from Product. I have tried 2 ways to achieve this: first attempt and second attempt. My simplifed related models in models.py: class Product(models.Model): product_id = models.CharField(max_length=6) color = models.ForeignKey(ColorParent, on_delete=models.SET_NULL, null=True) collection = models.ForeignKey(ProductCollection, on_delete=models.SET_NULL, null=True) @property def get_distributors(self): return Distributor.objects.filter(distributor__products=self).count() def __str__(self): return self.product_id class FinishType(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class ProductFinishType(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) market = models.ForeignKey(Market, on_delete=models.CASCADE) finish_types = models.ManyToManyField(FinishType) def __str__(self): return '%s - %s' % (self.product, self.market) class ProductAlias(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) market = models.ForeignKey(Market, on_delete=models.CASCADE) name = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return '%s - %s' % (self.product, self.name) My serializers.py: class ProductGridSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField(source='get_name') finishing = serializers.SerializerMethodField('get_finish_types') distributor = serializers.ReadOnlyField(source='get_distributors') @staticmethod def get_name(obj): return [pa.name for pa in obj.productalias_set.all()] @staticmethod def get_finish_types(obj): return [pft.name for pft in obj.productfinishtype_set.all().select_related('finish_types')] # first attempt class Meta: model = Product fields = ['id', 'product_id', 'name', 'collection', 'finishing', 'distributor'] First attempt works for name field which fetches ProductAlias's name but gives me this error: FieldError at /api/product_grids/ Invalid field name(s) given in select_related: 'finish_types'. Choices are: product, market My get_finish_types() on second attempt: @staticmethod def … -
How to save csv datetime string into Django model field
I want to store DateTimeField data from csv to my model field but I am getting error RuntimeWarning: DateTimeField Applications.submitted_at received a naive datetime (2020-01-30 11:08:20.429620) while time zone support is active. RuntimeWarning) my models.py submitted_at = models.DateTimeField(default=datetime.now, blank=True) form_fill_up_datetime = models.DateTimeField(auto_now=True, auto_now_add=True), how can I resolve this issue? here is my function to convert csv string data into datetimefield def date_check(data):# if data is None: print("Date Field is empty") return try: try: date_format1 = '%m/%d/%Y %H:%M:%S' date_obj = datetime.datetime.strptime(data, date_format1) return date_obj except ValueError: print('Incorrect data format, should be YYYY-MM-DD') date_format2 = '%Y-%m-%d %H:%M:%S' date_obj = datetime.datetime.strptime(data, date_format2) return date_obj except Exception as e: print(e) return -
Python Django Rest API
I have the below requirements. Please guide me how to achieve it. 1) Need to build an API using python Django rest framework. API will be shared with a team to post data. 2) The incoming data will be captured on the fly without saving it in database. Once received a new data, it will trigger a function and it will be sent to other tool. -
How GET request data without login jwt django rest-framework
I'm using Django rest-framework for API's and I want to secure my APIs. These API's are only GET requests that are populated on web pages. I saw some solutions like JWT but for this first, I've to login and then get data by its access token. I want to get data without login, web pages first send a request to login and get token and then use this token to get data, is time taking and make web pages slow. If there is another way please mention. -
How to compute Sum of an aggregate with Django?
I'm currenlty trying to compute the score of a Survey in SQL side only to be able to order survey by their scores, my current logic is: Compute the real coeficient of my Answer Make the sum of that coeficient for my Question (which can have multiples Answer so i use Sum) compute the ammount of points of my whole Survey based on the sum of all Question points (Question.point * sum(Answer.coef)) basicaly Survey.objects.annotate( answerresponse__realcoef=models.Case( models.When(answerresponse__coef__isnull=True, then=models.F('answerresponse__answer__coef')), models.When(answerresponse__coef__isnull=False, then=models.F('answerresponse__coef')), output_field=models.FloatField(), ) ).annotate( answerresponse__realcoef_sum=models.Sum( models.F('answerresponse__realcoef') ) ).annotate( points=models.Sum( models.F('answerresponse__realcoef_sum') * models.F('answerresponse__answer__question__points'), output_field=models.IntegerField() ), maxpoints=models.Sum('sections__question__points') ) the database schema is something like: Survey > Sections > Questions (points) > Answer (coef) > AnswerResponse (coef override) and i get the following error: FieldError: Cannot compute Sum('<CombinedExpression: F(answerresponse__realcoef_sum) * F(answerresponse__answer__question__points)>'): '<CombinedExpression: F(answerresponse__realcoef_sum) * F(answerresponse__answer__question__points)>' is an aggregate which is understand as "That sql part was not executed yet so you cannot rely on it" is it possible to achieve that by keeping in the SQL side only ? -
i am getting the error while installing the requirements folder in collab notebook for speech emotion recognition
first of all i am cloning the github project for speech emotion recognition '''!git clone https://github.com/marcogdepinto/Django-Emotion-Classification-Ravdess-API.git''' then installing the requirements using the following code '''%pip install utils %cd /content/Django-Emotion-Classification-Ravdess-API %pip install -r requirements.txt ''' then the following output is comming: ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. i have searched everywhere but couldnot find any solution. plz help me. Thanks in advance. -
How can to generate LazyDatetime and convert it to string?
Link to source code of lazy function I have a field in database: paid_at = models.DateTimeField() I try to generate lazy datetime for this field paid_at = lazy(datetime.date.today, datetime.date) I generate date (30.01.2020). But I get error TypeError: expected string or bytes-like object. How can I generate datetime? How can I fix error TypeError: expected string or bytes-like object? -
Not able to send checkbox data from all pagination in datatable from template to view in django
I have a datatable in my django template in which there is a checkbox next to every row to send the row data to a view function to make some mass updations in django model. But problem is if the multiple rows are on the same page in pagination then i can send the data accurately BUT if i select row 2 from page 1 and row 5 from page 3 only the row value from page 3 will be sent to the view function.! TEMPLATE.HTML {% block jquery %} <script type="text/javascript" class="init"> $(document).ready( function ($) { var $submit = $("#updiv").hide(), $cbs = $('input[name="updelegate"]').click(function() { $submit.toggle( $cbs.is(":checked") ); }); $('#myTable').DataTable({ dom: 'lBfrtip', "pageLength": 1, "language": { "emptyTable": "No Delegates Available", "sSearch": "Search Delegates: ", "info": " Showing _START_-_END_ out of Total _TOTAL_ Delegates", } }); }); </script> {% endblock %} <form id="myForm" action="{% url 'mass-delegates' %}" method="POST"> {% csrf_token %} <table id="myTable" class="table table-striped table-bordered" style="width:100%"> <thead class="thead-dark"> <tr> <th></th> <th scope="col">#</th> <th scope="col">Name</th> <th scope="col">Email</th> <th scope="col">Phone</th> <th scope="col">Company</th> <th scope="col">Designation</th> <th scope="col">Address</th> <th scope="col">City</th> <th></th> <th></th> </tr> </thead> <tbody> {% for del in delegates %} <tr> <td> <label class="container"> <input type="checkbox" id="updelegate" name="updelegate" value="{{ del.id }}"> <span class="checkmark"></span> … -
customization in Django admin site
How to change the placement / arrangement of the textbox or field? Just like in the picture: this is my models.py class StudentProfile(models.Model): Image = models.ImageField(upload_to='images',null=True,blank=True) Username = models.CharField(max_length=500,null=True,blank=True) Password = models.CharField(max_length=500,null=True,blank=True) lrn = models.CharField(max_length=500,null=True) Firstname = models.CharField(max_length=500,null=True,blank=True) Middle_Initial = models.CharField(max_length=500,null=True,blank=True) Lastname = models.CharField(max_length=500,null=True,blank=True) Parent_Users = models.ForeignKey(ParentsProfile, related_name='+', on_delete=models.CASCADE,null=True,blank=True,) Gender = models.CharField(max_length=500,null=True,blank=True) Birthday = models.CharField(max_length=500,null=True,blank=True) Place_Of_Birth = models.CharField(max_length=500,null=True,blank=True) Citizenship = models.CharField(max_length=500,null=True,blank=True) Education_Levels= models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) Religions = models.ForeignKey(Religion, related_name='+', on_delete=models.CASCADE,null=True,blank=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) my admin.py @admin.register(StudentProfile) class StudentProfile(admin.ModelAdmin): list_display = ('lrn','Firstname', 'Middle_Initial', 'Lastname', 'Request') ordering = ('pk',) search_fields = ('lrn','Firstname','Lastname') -
How to create a comment form using GenericForeignKey in template?
I want to create a comment form for my template using GenericForeignKey relation and i want to show post commnets in template. As i am a newbie i can't understand going through the documentation. Here is my thnigs models.py from django.contrib.contenttypes.fields import GenericForeignKey,GenericRelation from django.utils import timezone class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') text = models.TextField(null=False, blank=False) def __str__(self): return self.text[:20] views.py def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) content_type = ContentType.objects.get_for_model(Post) obj_id = post.id comments = Comment.objects.filter( content_type=content_type, object_id=obj_id) return render(request, 'post_detail.html', {'post': post, 'comments': comments}) -
Database hits for related object in get_absolute_url in django
I'm building an app that lists podcasts and their episodes. On the podcast page, I need to list episodes with links to the individual episode pages. To make human readable URLs, i'm using the slug for both the podcast and the episode. This is causing a lot of database hits. Here's the get_absolute_url function: def get_absolute_url(self): kwargs = { 'show_slug': self.podcast.slug, 'pk': self.id, 'slug': self.slug } return reverse('episode_page', kwargs=kwargs) How do I make this more database efficient, because for shows with 100s of episodes, this is querying the database a lot. -
Django request post in internationalization
When i send a request POST in my url, django return me a GET response because of internationalization. I have two language, french and english. Put i need to work with post request. I put an image with django http server log below. -
For loop with queryset in django
I'm building an app which lists episodes and categories for a podcast. Model relationships are set up this way: models.py class Podcast(models.Model): ... class Category(models.Model): ... podcast = models.ForeignKey(Podcast, on_delete=models.CASCADE) ... class Episode(models.Model): ... podcast = models.ForeignKey(Podcast, on_delete=models.CASCADE) categories = models.ManyToManyField(Category) ... I'm pulling a list of episodes for a podcast, organized by category: def episodes_by_category(self): #Self is a podcast object category_list = [] for category in self.category_set.all(): category_list.append({ 'category': category, 'episodes': self.episode_set.all().filter(categories=category), 'count': self.episode_set.all().filter(categories=category).count(), }) return sorted(category_list, key = lambda i: i['count'],reverse=True) In a DetailView This is causing a significant number of database queries. Here's how it's happening: views.py class PodcastPage(DetailView): model = Podcast template_name = 'dashboard/public/podcast_page.html' def get_context_data(self, **kwargs): context = super(PodcastPage, self).get_context_data(**kwargs) context['episodes'] = self.get_object().get_episodes[:10].prefetch_related('categories') return context template {% for episode_batch in podcast.episodes_by_category %} {% include "dashboard/public/_sidebar_top_category_list.html" %} {% endfor %} What can i optimize about that logic to make it more efficient and hit the database less? -
Django ajax request, how to show the html-page
ein javascript sendet ein ajax zu der view.py die view.py rendert und return daraufhin a new html page wie kann die neu gerenderte seite nun anzeigen? was muss ich in den success:function (data){} schreiben? -
Celery: Abort or revoke group in django celery
I'm using django celery. I know i can revoke task by using below code app.control.revoke(task_id, terminate=True) Can i use above code to remove group if the how can i get group id -
Stacking Multiple columns into one in django excel sheet export
I am exporting a model into a .xls file using django. But i want to stack multiple columns under one column. Example : If my xls sheet contains 10th grade information, like school, roll. no. , etc.. and same details for 12th grade (name, roll no, etc..), I want to group school, roll. no. into a column called 10th, and similarly for 12th. Any help will be appreciated. -
How to reassign 'host' for the root user of a docker mysql instance
I have two docker instances, one for the API and one for the DB of a project. I was able to run both without issues, but today I wasn't able to. The DB instance builds without issue, but the API is unable to communicate with it, due to the following error: django.db.utils.OperationalError: (1130, "Host '172.x.x.x' is not allowed to connect to this MySQL server") Some googling led me to check the host for the root user, which gives me: SELECT host from mysql.user where User='root'; +-----------+ | host | +-----------+ | localhost | +-----------+ 1 row in set (0.00 sec) Below is docker-compose.yml: version: "3" services: db: container_name: db image: mysql:5.7 ports: - "3336:3306" environment: MYSQL_ROOT_PASSWORD: *** MYSQL_USER: *** MYSQL_PASSWORD: *** MYSQL_DATABASE: *** restart: always command: [ "mysqld", "--character-set-server=utf8mb4", "--collation-server=utf8mb4_unicode_ci", ] api: container_name: api build: context: ../../ dockerfile: ./etc/docker/Dockerfile ports: - "8000:8000" depends_on: - db restart: always So, I have a few questions: Any idea why the API instance's IP changed? I'm assuming it changed, since it was able to connect without issues since yesterday. Is there a way to solve this issue via docker-compose/Makefile? I was able to ssh into the DB instance and change the host manually, but … -
I have try to apply "SimpleListFilter" on "InputFilter" class but i was getting HTML content in flters?
class InputFilter(admin.SimpleListFilter): template = 'nyc-theme/lms/templates/admin/course_enrollment/input_filter.html' def lookups(self, request, model_admin): # Dummy, required to show the filter. return ((),) def choices(self, changelist): # Grab only the "all" option. all_choice = next(super().choices(changelist)) all_choice['query_parts'] = ( (k, v) for k, v in changelist.get_filters_params().items() if k != self.parameter_name ) yield all_choice class SupervisorNameFilter(InputFilter): title = 'Supervisor Name' parameter_name = 'supervisor' enter image description here def lookups(self, request, model_admin): kwargs = { 'profile__supervisor_name__isnull': False } if 'profile__agency__id__exact' in request.GET: agency_id = request.GET['profile__agency__id__exact'] kwargs['profile__agency__id__exact'] = agency_id if 'division' in request.GET: division_id = request.GET['division'] kwargs['profile__division__id__exact'] = division_id users = model_admin.model.objects.filter(**kwargs).distinct() return [(user.profile.supervisor_ernumber, user.profile.supervisor_name) for user in users] def queryset(self, request, queryset): if self.value(): return queryset.filter(profile__supervisor_name__icontains=self.value()) class SupervisorERNFilter(InputFilter): title = 'Supervisor ERN' parameter_name = 'ern' def queryset(self, request, queryset): if self.value(): return queryset.filter(profile__supervisor_ernumber__icontains=self.value()) -
How to get a gmail profile image belong to a user?
I am working on one of the Django project where I have used social_django framework provided by the Django team for single sign-on with google, Now my requirement is to fetch the profile image related to that Gmail account Link of documentation for single sign-on https://python-social-auth.readthedocs.io/en/latest/configuration/django.html setting.py INSTALLED_APPS = [ .... 'social_django' ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', 'social_core.backends.google.GoogleOpenId', 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.debug.debug', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details', 'social.pipeline.debug.debug', ) SOCIAL_AUTH_GOOGLE_OAUTH2_IGNORE_DEFAULT_SCOPE = True SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile' ] views.py @login_required @transaction.atomic def update_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() return HttpResponseRedirect('/') else: messages.error(request, ('Please correct the error below.')) else: user_form = UserForm(instance=request.user) profile_form = ProfileForm(instance=request.user.profile) return render(request, 'testapp/profile.html', { 'user_form': user_form, 'profile_form': profile_form }) models.py @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() form.py from django import forms class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email',) class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('bio','location','birth_date') output When I used to log in with my Gmail account then somehow I get this data {'access_token': ---, … -
Connecting to MySQL from a Django project in Visual Studio Community 2019
I'm trying to connect to MySQL database from a Django project and I have this error: "django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?". I have already installed mysqlclient with this command: pip install mysqlclient In my Django project's settings.py file I have changed the database to this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_django', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3306', } } I'm using Visual Studio Community 2019. Django version: 2.2.9. Python version: 3.8.1 & Xampp for the MySQL. Any help would be appreciated! -
Django authenticates users when it should not
I am encountering a very odd issue on my Django app. I have a very simple form with an 'email' field that the user can use if he didn't received the activation link, to send it again. Everything works fine: my program checks if the email exists and if it does, it checks if the user isn't already active. If the user exists and isn't active, then Django sends an activation email to the user. But when the user clicks the "send email" button, Django logs him in shortly, because when the user then goes to another page he's not logged in anymore. It is maybe important to say that the user is logged EVERYTIME the account exists, even if the account is inactive, or if the user never entered the password for this account. I can't figure why is the app behaving this way. Does anyone have an idea how to solve my problem? User not logged in and wants to send activation link User was actually already active, and it logged him in when it shouldn't View associated to this page: def reactivate(request): if request.user.is_authenticated: return redirect('home') post = False if request.POST: post = True if request.POST['email']: try: … -
How not to show the password when changing the user?
I have a custom UserAdmin with custom fileds. When i add new user it is ok. But when i want to change user info i see his hashed password. How not to show the password? It's my overriding User admin. class UserAdminForm(forms.ModelForm): middle_name = forms.CharField(label='Отчество', empty_value='1 ', required=False) class Meta: labels = { 'last_name': 'Фамилия', 'first_name': 'Имя', 'password': 'Пароль', } class UserAdmin(admin.ModelAdmin): form = UserAdminForm fields = ['username', 'password', 'last_name', 'first_name', 'middle_name', 'groups'] list_display = ['username', 'last_name', 'first_name', 'url_get_money_from_user'] def url_get_money_from_user(self, obj): return format_html('<a href="/admin/fbp_common/person/{}/change/">{}</a>', obj.person.id, 'Списать средства') url_get_money_from_user.allow_tags = True url_get_money_from_user.short_description = 'Ссылка для списания денежных средств' def save_model(self, request, obj, form, change): obj.is_staff = True obj.set_password(form.data['password']) obj.save() -
Django row not updating trow views.py
RefferCheck = Users.objects.get(username=str(request.POST['reffer'])) if RefferCheck: if empty(RefferCheck.left): RefferCheck.left = str(request.POST['username']) RefferCheck.save() I am trying to update a single row in Database. but it not working and don't show any error Too. Note : I am not using Django forms i am using custom html forms.