Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass a list as value in .env file using python-dotenv
I'm using python-dotenv and I could not find a way to set a list (python style) to a variable. Currently, the list supplied is considered as a string and not a list. I understand the work around is to generate the list in settings.py which I would prefer not to. In .env file I tried ALLOWED_HOSTS=['xxx.xx.xx.xxx', 'example.com', 'www.example.com'] ALLOWED_HOSTS="['xxx.xx.xx.xxx', 'example.com', 'www.example.com']" In settings.py import os from dotenv import load_dotenv load_dotenv() ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS') # Expected ['xxx.xx.xx.xxx', 'example.com', 'www.example.com'] # but it gets a string which makes django to throw an Invalid Host error. Is there a native way to pass a list of values to env variables in python-dotenv? -
Getting error : Unexpected exception occurred: templates/email.txt in django email
When i am trying to send HTML email, i am getting error : Unexpected exception occurred: templates/email.txt, can anyone please help me why i am getting this error ? here i have attached my whole code. email.txt Click <a href="">here</a> to signup for the company email.html Click <a href="">here</a> to signup for the company views.py # Send Email subject = 'Invited to Trial Risk' msg_plain = render_to_string('templates/email.txt', {'user_id': user_id}) msg_html = render_to_string('templates/email.html', {'user_id': user_id}) send_mail( 'Invited to Trial', msg_plain, '****@gmail.com', [user_email], html_message=msg_html, ) -
Unable to save salary input field to model in Django
I have a registration form that allows a user to enter their salary and save it within my model. I am using Django-money in order to store the salary field. However, after submitting the form, I am getting this error: Object of type Money is not JSON serializable This is my code: models.py: from phonenumber_field.modelfields import PhoneNumberField from djmoney.models.fields import MoneyField class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key=True, related_name = 'register') salary = MoneyField(max_digits=14, decimal_places=2, default_currency='USD') How can I avoid the error and save the salary data to my model? -
How to display the model's "name" field using the ModelChoiceField
I have the following model class MyObject(models.Model): name = models.CharField(max_length=200, unique=True) type = models.CharField(max_length=20, choices=(('Type 1', 'Type 1','Type 2','Type 2')), null=False) I would like to let the user pick instances of MyObject, so i have created a form: class ClassifierSelectMultiForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) myObjects = MyObject.objects.all() self.fields["pick_model"] = ModelChoiceFieldCustom(myObjects) When picking the instances, I want the user to be able to see the "name" field so I have overwritten the label_from_instance method. class ModelChoiceFieldCustom(ModelChoiceField): def label_from_instance(self, obj): return obj.name Output (unexpected): I've tried changing the label_from_instance to return obj.type instead obj.name. Output (expected): How can i display the name attribute in the form? -
Django simple history inheritance getting from parent to child history
I am trying to use django-simple-history for keeping state of an Object. Let's say i have the following: class Parent(models.Model): fields... history = HistoricalRecords(inherit=True) class Child(Parent): fields... class Invoice(models.Model): fields... parent_history = models.ForeignKey("app.HistoricalParent", blank=True, null=True, on_delete=models.PROTECT, help_text="This keeps the state of the Child when Invoice is generated") parent = models.ForeignKey(Parent, blank=True, null=True, on_delete=models.PROTECT) # can be removed so foreign key loop gets eliminated How can i reach from Invoice to Child? Invoice.objects.get(id=1).parent_history.child Does not work and raise AttributeError: 'HistoricalParent' object has no attribute 'child' and this is how i am reaching Child from Parent Invoice.objects.get(id=1).parent.child I can't find the foreign key from HistoricalChild to HistoricalParent. Am i missing something? Does django-simple-history works some other way? -
Django fix existing database according to migrations
I inherited a django (1.11.6, database PostgreSQL) project and I am new with it. Recently I noticed that some tables differ from the ones generated by manage.py sqlmigrate for instance, manage.py inspectdb returns class TheClass(models.Model): id = models.IntegerField(primary_key=True) ... and migrations have: migrations.CreateModel( name='TheClass', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ... In addition, they have different constraint names ans so on, column names are correct. I think this is the result of incorrect transfer. And I want to fix the table in accordance with migrations leaving the data untouched. I tried using sqldiff, but it returned no differences and I didn't manage to find the answer. -
Use model information before migration
I'm trying to write a serializer in DRF which uses another before for a choicelist. However when I try to migrate (initially) I get an error because the serializer is trying to query for a table before it's created: from api.models.stock import Stock from rest_framework import serializers class ChartSerializer(serializers.Serializer): symbol = serializers.ChoiceField( choices=Stock.objects.values_list('symbol', flat=True)) option = serializers.ChoiceField( choices=['sparkline', '1d', '1w', '1m', '6m', '1y', '2y']) The error is: django.db.utils.ProgrammingError: relation "api_stock" does not exist LINE 1: SELECT "api_stock"."symbol" FROM "api_stock" How can I change this? Do I need to check if Stock has been created before maybe? -
Django ORM specifc query
I have 2 django models: class TelegramUser(models.Model): telegram_id = models.IntegerField() telegram_username = models.TextField(max_length=255, default=None, blank=True, null=True) first_name = models.TextField(max_length=255, default=None, blank=True, null=True) last_name = models.TextField(max_length=255, default=None, blank=True, null=True) has_blocked = models.BooleanField(default=False) class DutyDate(models.Model): date = models.DateField(default=None, blank=True, null=True) telegram_user = models.ForeignKey(TelegramUser, on_delete=models.SET_NULL, null=True) group = models.ForeignKey(UserGroup, on_delete=models.CASCADE, null=True) mark = models.FloatField(max_length=255, default=0) is_open = models.BooleanField(default=True) I need to get all users, who has less than 3 assigned DutyDates. Can I do it with one query and how? -
Filtering a many-to-many relationship with Django's Q query
I have a model class Book(models.Model): title = models.CharField(max_length=200) authors = models.ManyToManyField(Author) class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) And I have a view class SearchResultsListView(ListView): model = Book context_object_name = 'book_list' template_name = 'book/search_results.html' def get_queryset(self): query = self.request.GET.get('q') return Book.objects.filter( Q(title__icontains=query) ) I can't figure out how to access foreignkeys. How do I do a Q query searching for say, "show me only books in which any authors of the book that have the query string in any part of their last name"? -
Automatically run python script in django project
I am developing a django project and I have a problem related to executing python files automatically. For instance, I have to update the database from DynamoDB to Sqlite3 but I only can do it by running command python "update.py" I read documents about crontab or something similar. I consider whether are there any other ways to do this kind of task? Thank you -
Django Ajax Post Request by Using Checkbox in CBV
I'm trying to send ajax post requests to my server to add or remove objects by using just checkboxes (not form). Here is a screenshot of what i got visually: https://pasteboard.co/IMHHSa6.png When i click any of the checkboxes i got http500 (internal server error) as response. In cmd i see the error that says there is no matching query: app1.models.Influencer.DoesNotExist: Influencer matching query does not exist. The things is im pretty sure that the object with that id is exist in the database. I spend many time by inspecting django's CSRF documentation and watching youtube videos about django-ajax examples. Here is my code: views.py: class InfluencerListView(LoginRequiredMixin, ListView): model = Influencer context_object_name = 'influencers' # not necessary, default is object_list def post(self, request, *args, **kwargs): inf_id = request.POST.get('inf.id') list_id = request.POST.get('list.id') i = Influencer.objects.get(id=inf_id) l = InfluencerList.objects.get(id=list_id) l.influencers.add(i) data = { 'result' : 'some result' } return JsonResponse(data) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) logged_in_user = self.request.user context['myLists'] = logged_in_user.lists.annotate(influencers_count=Count('influencers')) return context models.py: class Influencer(models.Model): # fields are not included for the sake of clarity class InfluencerList(models.Model): name = models.CharField('Name:', max_length=20, blank=False) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lists') influencers = models.ManyToManyField('Influencer', related_name='lists') scripts.js function getCookie(name) { var cookieValue = null; if (document.cookie … -
How to create modules in django?
How to create modules in Django and import them. I want to create some modules like in python and they import them to Django's project. Let the module be a File A: class Module(): ... File views.py How to import the Module? -
Why Django can't connect to RabbitMQ after Lubuntu restart?
I'm using: RabbitMQ 3.8.2 Erlang 22.2.1 Django 1.11.4 Celery 4.1.0 Lubuntu 18.04 bionic After restarting OS I'm getting error from Django: pika.exceptions.ConnectionClosed: Connection to 127.0.0.1:5672 failed: [Errno 111] Connection refused I found that command sudo rm -rf /var/lib/rabbitmq/mnesia/ fix this problem, but I must to do it on every login. What I'm doing wrong? -
django-sendgrid-v5 Everything seems to work fine but mails don't get delivered
I'm using the django-sendgrid-v5 package to send mails in django. Everything works fine but the mail never reaches to the inbox, neither spam. Here are my current configurations: .env file: EMAIL_BACKEND='sendgrid_backend.SendgridBackend' SENDGRID_API_KEY='SG.the_rest_of_the_api_key' settings.py file: EMAIL_BACKEND = env('EMAIL_BACKEND') SENDGRID_API_KEY = env('SENDGRID_API_KEY') SENDGRID_SANDBOX_MODE_IN_DEBUG=False and my mail function: from django.core.mail import send_mail send_mail( mail_subject, message, 'noreply.cpsb@nyeri.go.ke', [to_email], fail_silently=False ) On sending the email, I get no error, but still the mail doesn't get delivered. What could I be missing? -
Getting error : AttributeError: 'dict' object has no attribute 'usertype'
When i am trying to get value from object, it gives me error AttributeError: 'dict' object has no attribute 'usertype', i can see i am getting proper result of queryset, but not able to fetch value from it, my queryset <QuerySet [{'usertype': 2}]> , here is my full code, can anyone please help me what's issue in that ? class Login(APIView): permission_classes = (AllowAny,) def post(self, request): username = request.data.get("username") password = request.data.get("password") if username is None or password is None: return Response({'success': False, 'error': 'Please provide both username and password'}, status=HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) # return Response({'success': True, 'user': user},status=HTTP_200_OK) if not user: return Response({'success': False, 'error': 'Invalid Credentials'}, status=HTTP_400_BAD_REQUEST) access_token, refresh_token = utils.generate_tokens(user) user_profile = UserProfile.objects.filter(user_id=user.id).values('usertype') print(user_profile[0].usertype) -
Render child page inside the base html template in Python Django
I am trying to render a template inside the base html page. Base html has the header, footer, menu common for the whole site. The middle section of the page has to come from the child page. I think I have everything right, but it is not working, what I am missing? project | ---templates/base.html ---templates/childpage.html base.html {% load static %} <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="{% static 'css/custom.css' %}"> </head> <body> {% block content %} {% endblock %} </body> </html> childpage.html {% extends "base.html" %} {% block content %} <form action="" method=""> </form> <br><br><br> <div class="something"> </div> {% endblock content%} views def home(request): return render(request, 'base.html') def askforchild(request): return render(request, 'childpage.html') urls urlpatterns = [ url(r'^admin/', admin.site.urls), url('', views.home, name='Site Home Page'), url('askforchild', views.askforchild, name='child page'), ] -
JsonResponse from Django not sending the mentioned key value pair to Reactjs
I am trying to fetch response from a Django API using react, but the key value pair which I am passing is not visible in the response. React fetch code handleClick(i) { . . . if (i != '=') { . . } else { // CODE TO FETCH FROM DJANGO API fetch('http://127.0.0.1:8000/solve/', { method: 'POST', body: {"expression":this.state.content} }).then((response)=>{ console.log(response)}) } } Python Code # Create your views here. @api_view(["POST"]) def solveExpression(expression_json): try: math_expr = expression_json.data["expression"] result = eval(math_expr) data = {"result":result} #This is the data I want to send to reactjs return JsonResponse(data) except Exception as e: return JsonResponse("Error:" + str(e), safe = False) But unfortunately the response I get doesn't have the key "result" in it. Kindly correct me where I am committing the mistake as I am quiet new to reactjs. -
OperationalError at /admin/movie/movieinfo/add/
database error: OperationalError at /admin/movie/movieinfo/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://localhost:8000/admin/movie/movieinfo/add/ Django Version: 2.1 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Users\admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 296 Python Executable: C:\Users\admin\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.0 Python Path: ['D:\project\portest', 'C:\Users\admin\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\admin\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\admin\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\admin\AppData\Local\Programs\Python\Python38-32', 'C:\Users\admin\AppData\Roaming\Python\Python38\site-packages', 'C:\Users\admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages', 'C:\Users\admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\win32', 'C:\Users\admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\win32\lib', 'C:\Users\admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\Pythonwin'] -
Annotate A object with the count of related B objects with Subquery
I am trying to annotate User with the count of delayed leads objects. The calculation of delayed leads is complex (uses RawSQL) implemented using a custom model manager. Hence, I am trying to implement this using a subquery. sq = Lead.delayed.filter(assigned_to_id=OuterRef('pk')) User.objects.annotate(num=Count(Subquery(sq.count()))) However, I keep getting this error: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. -
Unable to view 100/all_rows in Pgadmin4
I am new to Postgres and Pgadmin4. I have previously used MySql(Phpmyadmin) which was very user-friendly. When I am trying to view the first 100 rows (or) all rows for that matter, only the first 12 rows are visible in the Pgadmin panel as shown in the below image. Can someone please tell, how to view the top 100 rows or 500 rows. -
Django signal to follow/unfollow
I have a signal that looks like this: @receiver([post_save, post_delete], sender=Following) def increment_follow_count(instance, created=False, **kwargs): if created: instance.follower.following_count += 1 instance.target.follower_count += 1 else: instance.follower.following_count -= 1 instance.target.follower_count -= 1 When a user follows another user, it works correctly. However, when that same user unfollows that user, only the person that the user followed (target) has their follower count decremented, but the user's following count is not decremented. Why is this behavior happening and how can I fix it? -
Elastic beanstalk error: Command failed on instance. Return code: 1
I am trying to deploy my django app on aws but i keep getting the following error: [Instance: i-********] Command failed on instance. Return code: 1 Output: (TRUNCATED)....6/site-packages/django/db/migrations/operations/fields.py", line 285, in state_forwards "%s.%s has no field named '%s'" % (app_label, self.model_name, self.old_name) django.core.exceptions.FieldDoesNotExist: classroom.itembatch has no field named 'width'. container_command 01_migrate in .ebextensions/db-migrate.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. Here's my db-migrate.config file container_commands: 01_migrate: command: "django-admin.py migrate --noinput" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: django_school.settings Why am I getting this error and how can I change this ? -
Inserting a values to DB takes too long
I'm receiving a data from upload form to views.py in Django and I'm saving it to a DB (MongoDB). But the data are too big, so it takes a lot of time and CPU. I found why it takes so long, but I'm not able to send this data by other means... this is my code csv_file = request.FILES["csv_file"] file_type = request.POST.get("type", "") file_data = csv_file.read().decode("utf-8") if file_type == "val3": lines = file_data.split("\n") items = [] item = "" for line in lines: column = line.split(',') try: item = kokyaku( # HERE I'm calling `kokyaku` model every time 顧客CD = int(column[0]), 顧客補助CD = int(column[1]), 顧客名称s=str(column[2]), 顧客名称=str(column[3]), 顧客名称カナ=str(column[4]), 法人名称=str(column[5]), 代表者名称=str(column[6]), 住所=str(column[7]), 電話番号=str(int(column[8])), 地区名称=str(column[9]), データマッチ用電話番号=int(column[10]), 契約状態=str(column[11]) ) items.append(item) except Exception as e: print(e) kokyaku.objects.bulk_create(items) I'm calling kokyaku model every time in loop, so its extremely slow... I tried to send it as list of dicts like this item = { "顧客CD" : int(column[0]), ..... } items.append(item) so I could avoid calling kokyaku every time - it maked process faster, but my model is not able to receive data in this format... What could I do? If possible I would like to use bulk_create to make it faster... Here is my models.py class … -
Refresh token missing for all users except app owner in google oauth
I'm using https://github.com/python-social-auth/social-app-django for gmail auth in my django app.But oauth returns refresh token only for the owner of the app(i.e when I log in). For rest of the users it is not returned. The refresh token is missing in the extra_data. The app is unpublished. Is that the reason for this weird behaviour? How should I overcome it? -
success_url from UpdateView to DetailView with pk in django
i make my own group permission page self with ListView to show django Group list with link to DetailView with pk and then give the change link to change the permissions with UpdateView. i want make the success_url of UpdateView to DetailView with pk, how to do this. my code like: views.py class GroupCreation(PermissionRequiredMixin, CreateView): permission_required = 'add_group' model = Group form_class = GroupCreateModelForm success_url = reverse_lazy('account:group_list') template_name = 'accounts/groups/group_creation.html' class GroupsListView(PermissionRequiredMixin, ListView): permission_required = 'view_group' allow_empty = True model = Group ordering = 'name' template_name = 'accounts/groups/groups_list.html' form = GroupCreateModelForm extra_context = {'form': form, } class GroupDetailView(PermissionRequiredMixin, DetailView): permission_required = 'view_group' model = Group template_name = 'accounts/groups/group_detail.html' class GroupUpdateView(PermissionRequiredMixin, UpdateView): permission_required = 'change_group' model = Group fields = ('permissions',) template_name = 'accounts/groups/group_update.html' success_url = reverse_lazy('account:group_detail') urls.py path('groups/', views.GroupsListView.as_view(), name='group_list'), path('groups/<int:pk>/', views.GroupDetailView.as_view(), name='group_detail'), path('groups/<int:pk>/change/', views.GroupUpdateView.as_view(), name='group_change'), path('groups/create/', views.GroupCreation.as_view(), name='group_creation'),