Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change part of the form inside the template by ajax
i have a small problem it is in Classified-Ads site by django when i make ads there are main form for title, descriptions, img , categorys and there are some special form for exmple:if the user choice cars categorys i wont to show some special form like Kilometers , Color , Body Type , Engine Capacity (CC) but if he choise mopile phone there are different forms will be showing like model , processor , ram I hope I can communicate the idea my solution is : make some special forms class like this forms.py class carf(forms.ModelForm): class Meta: model = catugry fields = ['name', 'main' ] class mobilef(forms.ModelForm): class Meta: model = catugry fields = ['name','sub', 'end' ] and in template make ajax code to send Id of choosing category <script> $("#id_main").change(function () { var url3= ("{% url 'ads:ff'%}") // get the url of the `load_cities` view var mainff = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url3, // set the url of the request (= localhost:8000/hr/ajax/load-cities/) data: { 'mainff': mainff, }, success: function (data2) { // `data` is the return of the `load_cities` view function $("#fff").html(data2); console.log(data2); … -
I can't seem to use the DateTimeField in django without errors
My django blog app has the parameters, title, pub-date, body and image. when i create a blog model on the admin page i get an error. here's what the code looks like. ProgrammingError at /admin/blog/blog/add/ column "pub_date" is of type integer but expression is of type timestamp with time zone LINE 1: ..._date", "image", "body") VALUES ('My first blog', '2020-04-0... ^ HINT: You will need to rewrite or cast the expression. Here is the model i created: ''' from django.db import models class Blog(models.Model): title = models.CharField(max_length=250) pub_date = models.DateTimeField() image = models.ImageField(upload_to='images/') body = models.TextField() ''' -
Django App deployed to Heroku - psycopg2.errors.NotNullViolation as data is not passed through Ajax
I have successfully deployed my app to Heroku but one feature is not working properly, although it's working good on my local env. From Heroku logs i can see the following: 2020-04-17T09:50:34.538062+00:00 app[web.1]: Internal Server Error: /shop/add_to_cart/11/ 2020-04-17T09:50:34.538078+00:00 app[web.1]: Traceback (most recent call last): 2020-04-17T09:50:34.538079+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute 2020-04-17T09:50:34.538079+00:00 app[web.1]: return self.cursor.execute(sql, params) 2020-04-17T09:50:34.538080+00:00 app[web.1]: psycopg2.errors.NotNullViolation: null value in column "quantity" violates not-null constraint 2020-04-17T09:50:34.538081+00:00 app[web.1]: DETAIL: Failing row contains (23, null, null, 23, 11). The mentioned quantity is passed through ajax: $('.add-product-to-cart').on('click', function (e) { e.preventDefault(); let product_id = $(this).attr('data-product-id'); let quantity = $('#input-product' + product_id).val(); let csrftoken = $('input[name=csrfmiddlewaretoken]').val(); $.ajax({ url: 'add_to_cart/' + product_id + '/', type: 'POST', data: { 'product_id': product_id, 'qty': quantity, 'csrfmiddlewaretoken': csrftoken, }, success: function (data) { alert("Produkt dodany"); } }); }); Again this code works on local. The html bit that ajax refers to, is as per below: <div class="bottom-area d-flex px-1"> <div class="m-auto w-100"> <form method="POST" action="{% url 'shop:add_to_cart' product.id %}" class="d-flex align-items-center justify-content-center" id="add-product-to-cart-form"> {% csrf_token %} <div class="d-flex align-items-center justify-content-start pr-2"> <input type="number" name="qty" id="input-product{{ product.id }}" class="quantity input-number py-0" value="{{ product.min_qty_value }}" min="{{ product.min_qty_value }}" max="500" step="{{ product.min_qty_value }}" style="padding: 0 0 0 10px; border-radius: … -
Unable to serve django static files using uwsgi to the nginx
I'm using uwsgi as the server and nginx as the reverse proxy for running the django project. Project structure is as follows(here i have listed only required folder/files): war ├── katana │ ├── wapps │ │ ├── app1 │ │ └── app2 │ └── wui │ ├── settings.py │ └── wsgi.py └── static ├── css │ └── test.css ├── img │ └── test.img └── js └── test.js The static configuration in settings.py is as follows: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] DATA_UPLOAD_MAX_MEMORY_SIZE = 10242880 STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') The wsgi.py is as follows: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "katana.wui.settings") application = get_wsgi_application() The uwsgi is server is started using: uwsgi -b 65535 --socket :4000 --workers 100 --cpu-affinity 1 --module katana.wui.wsgi --py-autoreload 1 The nginx conf is as follows: events { worker_connections 1024; ## Default: 1024 } http { include conf/mime.types; # the upstream component nginx needs to connect to upstream uwsgi { server backend:4000; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8443 ssl http2 default_server; # the domain name it will serve for server_name … -
How to make channel client in views.py?
I am making a chatbot in views.py will receive an HTTP request by the user and views.py interacts with the bot and return to the user. I am using channels to communicate between views.py and chatbot API. following is the views code and channel consumer code. #views.py @api_view(['POST']) def conv(request): ws = create_connection(url) ws.send({"message":request.data["msg"]}) rec = ws.recv() return {"msg" : rec} #consumers.py class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) After receiving from the channel the connection disconnects and I am unable to maintain chat session on the consumer end. -
testing stripe on boarding view django
i am trying to test the view pasted below. However i can't figure out how i would go about doing this. I can get so far as mocking the get request, but how can i grab the values from the view to test them against values they should be. Here is the view : class StripeAuthorizeView(LoginRequiredMixin, View): def get(self, request): url = 'https://connect.stripe.com/express/oauth/authorize?' user = self.request.user if user.account_type == 'Business': business_type = 'company' else: business_type = 'individual' params = { 'response_type': 'code', 'scope': 'read_write', 'client_id': settings.STRIPE_CONNECT_CLIENT_ID, 'redirect_uri': f'http://127.0.0.1:8000/accounts/stripe/oauth/callback', 'stripe_user[email]' : user.email, 'stripe_user[business_type]' : business_type, 'stripe_user[url]' : 'http://127.0.0.1:8000/accounts/user/%s/' %user.pk, } url = f'{url}?{urllib.parse.urlencode(params)}' return redirect(url) I need to be able to test that the url is the correct url, the view is sending the correct client id and pre filling in the correct fields, eg user.email etc. The scary thing is if i can't write some tests for it, if someone was to accidentally change them it will cripple my platform. Really need to be testing that the view is getting passed the correct data to the stripe api. Any help will really be helped. -
allow html file to be shown in iframe django
I am working on this Django project and I am trying to show the html file 'addition.html' in an iframe on 'main.html'. If I understand things correctly, I have to specify frame-ancestors options in my CSP options (as e.g. explained here). However, I do not fully understand: Which file can the CSP be specified? What line of code is needed in order to allow my main page to show the addition in the frame. Any help is much appreciated. -
Can't get the DeleteView of a post in a social network project
I am building a simple social network in django. In the "home" of my social, I have the list of all posts published by all users, with author and publishing date. Under each post of the logged user, a "delete" button appears. If the user clicks on it, it should return a specific view of that post, with a message like "do you really wish to delete this post?" However, as I click on it, the code returns this error: NoReverseMatch at /posts/delete/7/ Reverse for 'single' with no arguments not found. 1 pattern(s) tried: ['posts/by/(?P[-\w]+)/(?P\d+)/$'] Why does it says that it cannot get the reverse for 'single' with no arguments, while in the template the delete button has a link to 'delete' view function? Here is my urls.py, inside urlpatterns: url(r'by/(?P<username>[-\w]+)/(?P<pk>\d+)/$', views.PostDetail.as_view(), name='single'), url(r'delete/(?P<pk>\d+)/$', views.DeletePost.as_view(), name='delete'), Here is my views.py: class DeletePost(LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView): model = models.Post select_related = ('user', 'group') success_url = reverse_lazy('posts:all') def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user_id = self.request.user.id) def delete(self,*args,**kwargs): messages.success(self.request,'Post Deleted') return super().delete(*args,**kwargs) Here is my piece of template showing the post and asking the user if he/she really wants to delete it: {% if user.is_authenticated and post.user.username == user.username %} <a href="{% url … -
ProgrammingError at /admin/group_manager/automaticgroup/
I have encountered this problem on my django admin page, I really don't understand what is happening but I'm unable to view my table content on the admin page in the django server and it is returning errors. I succeeded in doing migrations, I wonder if it did migrations well but then they confirmed that no new migrations was detected. So, this is what happens, after running: python manage.py runserver It returns this: Starting development server at http://127.0.0.1:8000/ and when I click on it and go to the admin section "http://127.0.0.1:8000/admin" and click on my newly created table, it returns this error page. Please could someone help me :-( This is a screenshot of my error message Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/group_manager/automaticgroup/ Django Version: 2.2 Python Version: 3.6.8 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'profile_manager.apps.ProfileManagerConfig', 'group_manager.apps.GroupManagerConfig', 'trip_manager.apps.TripManagerConfig', 'relationship_manager.apps.RelationshipManagerConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',`enter code here` 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\Glory\Desktop\django\opentravels\venv\lib\site-packages\django\db\backends\utils.py" in _execute 84. return self.cursor.execute(sql, params) File "C:\Users\Glory\Desktop\django\opentravels\venv\lib\site-packages\django\db\backends\mysql\base.py" in execute 71. return self.cursor.execute(query, args) File "C:\Users\Glory\Desktop\django\opentravels\venv\lib\site-packages\MySQLdb\cursors.py" in execute 209. res = self._query(query) File "C:\Users\Glory\Desktop\django\opentravels\venv\lib\site-packages\MySQLdb\cursors.py" in _query 315. db.query(q) File "C:\Users\Glory\Desktop\django\opentravels\venv\lib\site-packages\MySQLdb\connections.py" in query 239. _mysql.connection.query(self, query) The above exception ((1146, "Table 'opentravels.group_manager_automaticgroup' doesn't exist")) … -
__init__ an got unxexpected keyword argument 'attrs' in Django
I know there are a lots of similar questions out there, but none of them solves my problem. So i have in forms.py: from django import forms from .models import Article class ArticleForm(forms.ModelForm): author = forms.CharField(widget=forms.TextInput(attrs={"placeholder":"Autor"})) class Meta: model = Article fields=[ "title", "author", "mainpart" ] But I get the Error: TypeError: __init__() got an unexpected keyword argument 'attrs' I'm really confused what's wrong. Thx for helping and stay healthy! -
How to get Django-Q to send a message once the broker has finished executing a task?
I have a django app that needs to send some big tasks to the backend to execute aysnchronously. I'm using django-q with redis for this. It works at a basic level - the task is sent to redis, django is no longer blocked waiting - but it does it silently. The app doesn't know when the task is complete, or if it has completed successfully. This makes it really brittle. I'm now trying to get a signal back from redis when the task is complete (successfully or not). Looking at the DjangoQ documentation, I've set up the following proof of concept: views.py import json from django.http import JsonResponse from django_q_tasks import async_task def testredisview(request): json_payload = {"message": "hello world!"} async_task("services.sleep_and_print", 10, hook='hooks.print_result') return JsonResponse(json_payload) services.py from time import sleep def sleep_and_print(secs): sleep(secs) print("task done") hooks.py def print_result(task): print((task.id, task.result)) When I run python3 manage.py qcluster and then hit the url 127.0.0.1:8000/testredis, 10 seconds later I get the JSON: message: "hello world!" and the django server shows: [Q] INFO Enqueued 1, so it's executing the service command successfully. However, the cluster shows: [Q] INFO Q Cluster -cluster_name- running. [Q] INFO Process-1:1 processing [-process_name-] 'task done' '(-task_id-, None)' [Q] INFO Processed [-process_name-] … -
Annotating every some data in a queryset
I am developping with Django and I am looking for a queryset somehow can do this operation : A queryset wich is returning 10000 objects , can calculate the average of each 1000 of the 10000 as well. the code that i am looking for as my knowledge seems like that: queryset=Model.objects.annotate(part=func(get 1000 objecs), average=Avg('Values')) I know annotate just calculates summary values for each item in the queryset , but in my case i just need to do it for every sliced part of the queryset so far. -
How to wrap Django SQL query with raw SQL
My users in Django can participate in contests in which they score points. I want to rank my users based on the sum of their three best contests. I have a working SQL query: SELECT id, sum(contest_points) as plus FROM ( SELECT ROW_NUMBER() OVER (PARTITION BY u.id ORDER BY c.points DESC), c.points as contest_points, u.id as id FROM ( user_user AS u LEFT OUTER JOIN contest_contest AS c ON (u.id = c.user_id) ) ) x WHERE row_number <= 3 GROUP BY id ORDER BY plus DESC; However, because there are potentially many filters which I want to apply (country, contest type), I want to use the Django ORM to generate the SQL. This is where I am so far: Contest.objects.annotate( rank=Window(expression=Rank(), partition_by=F('user_id'), order_by=F('points').desc() ) I can annotate the contests based on their respective rank for the user, but Django prevents me from filtering contest based on the rank, as you are not allowed to filter after a window function. In pure SQL, this is not a problem as I can just wrap the entire query. This is not possible in Django, as subquery is only allowed to return a single column. My idea is to custom wrap the inner SQL … -
Django UpdateView not updating instance
Basically, when i look at the networking tab in inspect element i can see that POST request was sent and the form data is valid, but the instance object isn't being saved class UpdateProfile(UpdateView): template_name = 'dashboard/edit-profile.html' form_class = UserForm success_url = None def get_object(self, queryset=None): return User.objects.get(username=self.kwargs['username']) def form_valid(self, form): self.instance = form.save(commit=False) self.instance.user = self.get_object() self.instance.save() return render(self.request, self.template_name, self.get_context_data()) I've tried to assigning the data from instance to model directly by getting it from get_object, still no effect. <form action="" class="tm-edit-product-form" method="post"> <div class="row mt-4 tm-edit-product-row"> <div class="col-xl-7 col-lg-7 col-md-12"> <div class="input-group mb-3"> <label for="{{ form.full_name.label }}" class="col-xl-4 col-lg-4 col-md-4 col-sm-5 col-form-label"> Full Name </label> {{ form.full_name }} </div> <div class="input-group mb-3"> <label for="{{ form.username.label }}" class="col-xl-4 col-lg-4 col-md-4 col-sm-5 mb-2"> Username </label> {{ form.username }} </div> <div class="input-group mb-3"> <label for="{{ form.email.label }}" class="col-xl-4 col-lg-4 col-md-4 col-sm-5 col-form-label"> Email </label> {{ form.email }} </div> <div class="input-group mb-3"> <label for="{{ form.description.label }}" class="col-xl-4 col-lg-4 col-md-4 col-sm-5 col-form-label"> Description </label> {{ form.description|as_crispy_field }} </div> <div class="input-group mb-3"> <label for="{{ form.ig.label }}" class="col-xl-4 col-lg-4 col-md-4 col-sm-5 col-form-label"> Instagram </label> {{ form.ig }} </div> <div class="input-group mb-3"> <label for="{{ form.fb.label }}" class="col-xl-4 col-lg-4 col-md-4 col-sm-5 col-form-label"> Facebook </label> {{ form.fb … -
Django creates but doesn't updates object with get_or_create() method
I have a model that looks like this and I try to update field average_entry_price but my problem is that there is no update although the object is created. As you can see created return a False. There is no error message and I think the syntax is correct since I first try to match on fields market andaccount, which seems to work fine because the object is created at the beginning, and then I say to Django update the remaining fieldaverage_entry_price`. Am'I missing something here? print('new value is', position['price']) obj, created = Position.objects.get_or_create( market=market, account=a, defaults={ 'average_entry_price': position['price'] }, ) print(obj.average_entry_price) print(created) Then it returns: new value is 7074.0 7.0 False models.py class Position(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='position', null=True ) market = models.ForeignKey(Market, on_delete=models.CASCADE, related_name='position', null=True ) average_entry_price = models.DecimalField(max_digits=8, decimal_places=1, null=True ) class Meta: verbose_name_plural = "Positions" def __str__(self): return str(self.market) -
Implementing Load Balancing in Django
I'm trying to implement Load Balancing in Django using Round robin method. At First I created model where I kept all instances and a sequence of each instance. My Model: class Load_Balancing(models.Model): id = models.AutoField(primary_key=True) instance = models.CharField(max_length=100) sequence = models.IntegerField() My database looks something like this: id | instance | sequence 1 http:localhost:1111 1 2 http:localhost:2222 2 3 http:localhost:3333 3 4 http:localhost:5555 4 I want to implement round robin algorithm to implement Load Balancing i.e at any instance I call GET request I get id 3 instance(If i make 4 post request) than 4 than 1 and so on. -
add account id with uuid (django.db.utils.ProgrammingError: column accounts_account.account_id does not exist)
im trying to add account id with uuid field class Account(AbstractBaseUser): account_id = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30) #other fields but when i try to createsuperuser it give the following error django.db.utils.ProgrammingError: column accounts_account.account_id does not exist LINE 1: ...nts_account"."id", "accounts_account"."password", "accounts_... i also did makemigrations and migrate database are : postgis in postgresql -
Django FilteredSelectMultiple change tooltip from forms.py
I want to ask about the method to change the title value(tooltip) of each option in the FilteredSelectMultiple widget unlink other widgets it doesn't work properly with attrs passed values. Initial options look like this: <option value="1" title="Math"> Math </option> I actually want to change value of both displayed text and title. I was able to change the displayed text with following code: class CoursesMultipleChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return "%s (%s)" % (obj, obj.Teacher_Code.count()) class InningInfoForm(forms.ModelForm): Course_Group = CoursesMultipleChoiceField(queryset=None, required=True, widget=FilteredSelectMultiple("Courses", is_stacked=False, attrs = {'title':'test'})) Here using custom CoursesMultipleChoiceField value is changed successfully. So now the output is: <option value="1" title="Math(3)"> Math(3) </option> Here option value is correct what I want but I also want to change the title dynamically like teacher name inside it. So the main question is how to change the title value differently like option value which I have done previously. Desired Output like: <option value="1" title="John, Sam, Ema"> Math(3) </option> -
Django is installed in virtual enviroment but gives ImportError: Couldn't import Django
Can this be configuration mismatch issues since we have copied the python project from my local machine (ubuntu 18.04) to server (ubuntu 16.04)? I have created project in pycharm IDE and added all required dependencies, so there is my application in that project and when I started server on my local machine and give call to web-service it returns me response with success. But when I moved that entire project structure to the server machine and also added all required dependencies again started server then it is giving me the above issue. -
How do I get queryset of this foreign key from id instead of unique_id?
I have a function in which I am passing list of unique_ids, and in this function I am getting a queryset of users_unique_ids in the following manner: def my_function(unique_ids): user_unique_ids = models.ThroughTableModel.objects.filter(users_id__in=unique_ids) # do something Here is my ThroughTableModel: class ThroughTableModel(models.Model): users = models.ForeignKey(User, to_field='unique_id') # other fields Now I want to use id instead of unique_id for this foreign key, but my_function will still receive unique_ids as the arguments. How can I change my filter to get user_ids instead of user_unique_ids? One way I thought was to get list of ids first and then passing it to the filter like this: def my_function(unique_ids): list_ids = models.User.objects.filter(unique_id__in=unique_ids).values_list('id') user_ids = models.ThroughTableModel.objects.filter(users_id__in=list_ids) # do something Is there a better way to achieve this without making the list_ids and directly using unique_ids in the filter? -
how to solve this error -Reverse for '' not found. '' is not a valid view function or pattern name.- i have used TemplateView function in url patterns
This is my views.py if request.user.is_superuser: return render(request, 'users/admin_profile.html', context) else: return render(request,'users/profile.html',context) This is how i defined the urlpattern path('admin_profile/', TemplateView.as_view(template_name='users/admin_profile.html'),name='admin_profile'), And my base.html where i used this url is here {% if user.is_authenticated %} {% if user.is_superuser %} <a class="nav-item link" href="{%url 'admin_profile'%}"><i class="fa fa-user" aria-hidden="true"></i> Profile</a> {% else %} <a class="nav-item link" href="{%url 'profile'%}"><i class="fa fa-user" aria-hidden="true"></i> Profile</a> {%endif%} <a class="nav-item link" href="{%url 'logout'%}"><i class="fa fa-sign-in" aria-hidden="true"></i> Logout</a> {% else %} <a class="nav-item link" href="{%url 'login'%}"><i class="fa fa-sign-in" aria-hidden="true"></i> Login</a> <a class="nav-item link" href="{%url 'register'%}"><i class="fa fa-user-plus" aria-hidden="true"></i> Register</a> {%endif%} -
Django: migration file depends on removed Django-APP
In a Django project I've been asked to remove completely an installed app; I've already: removed all code references removed from INSTALLED_APPS checked there are no db tables around so far, so good; the problem raises when running: $> python manage.py migrate since there is a migration file around with the following: class Migration(migrations.Migration): dependencies = [ ('THE REMOVED APP', '0001_initial'), ... operations = [ ... It says: django.db.migrations.exceptions.NodeNotFoundError: Migration xxx.yyy dependencies reference nonexistent parent node ('THE REMOVED APP', '0001_initial') May I change the migration file and commit the following? @@ -14,7 +14,6 @@ class Migration(migrations.Migration): dependencies = [ - ('THE REMOVED APP', '0001_initial'), ] -
AttributeError: 'bool' object has no attribute 'ensure_connection'
I have custome code wait for db Command file wait_for_db.py: import time from django.db import connection from django.db.utils import OperationalError from django.core.management.base import BaseCommand class Command(BaseCommand): """Django command that waits for database to be available""" def handle(self, *args, **options): """Handle the command""" self.stdout.write('Waiting for database...') db_conn = None while not db_conn: try: connection.ensure_connection() db_conn = True except OperationalError: self.stdout.write('Database unavailable, waiting 1 second...') time.sleep(1) self.stdout.write(self.style.SUCCESS('Database available!')) File for test command test_commands.py: from unittest.mock import patch from django.core.management import call_command from django.db.utils import OperationalError from django.test import TestCase class CommandsTestCase(TestCase): def test_wait_for_db_ready(self): """Test waiting for db when db is available""" with patch('django.db.utils.ConnectionHandler.__getitem__') as gi: gi.return_value = True call_command('wait_for_db') self.assertEqual(gi.call_count, 1) @patch('time.sleep', return_value=None) def test_wait_for_db(self, ts): """Test waiting for db""" with patch('django.db.utils.ConnectionHandler.__getitem__') as gi: gi.side_effect = [OperationalError] * 5 + [True] call_command('wait_for_db') self.assertEqual(gi.call_count, 6) When I run this code using docker then get error with message: ERROR: test_wait_for_db (core.tests.test_commands.CommandsTestCase) Test waiting for db ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python3.8/unittest/mock.py", line 1348, in patched return func(*newargs, **newkeywargs) File "/app/core/tests/test_commands.py", line 24, in test_wait_for_db call_command('wait_for_db') File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 168, in call_command return command.execute(*args, **defaults) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/core/management/commands/wait_for_db.py", line 17, in handle connection.ensure_connection() File … -
How to resize uploaded image to DigitalOcean Spaces using Django?
I have built a blog application using Django with the additional functionality of uploading post thumbnails. Everything worked great in development, however, when I pushed to production and started saving and serving images using DigitalOcean Spaces, the images don't seem to get uploaded and I get a server error. Can anyone please tell me how I can adapt my code to make this work? This is my current configuration: models.py def image_path(instance, filename): basefilename, file_extension = os.path.splitext(filename) chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890' randomstr = ''.join((random.choice(chars)) for x in range(10)) #return 'listings/{listing}/{randomstring}{ext}'.format(listing = instance.slug, randomstring = randomstr, ext = file_extension) return 'posts/{randomstring}.jpg'.format(randomstring = randomstr) class Post(models.Model): title = models.CharField(_('title'), max_length=50) author = models.ForeignKey(Author, on_delete=models.CASCADE) slug = models.SlugField(_('slug'), unique=True, null=True, blank=True) body = models.TextField(_('body')) image = models.ImageField(_('image'), blank=True, upload_to=image_path, validators=[validate_image]) date_created = models.DateTimeField(_('date created'), auto_now_add=True) date_modified = models.DateTimeField(_('date modified'), auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.image: img = Image.open(self.image.path) if img.mode != 'RGB': img = img.convert('RGB') if img.width > 100: ratio = img.width / img.height height = 100 / ratio output_size = (100, height) img.thumbnail(output_size) img = ImageOps.exif_transpose(img) img.save(self.image.path, optimize=True, quality=90, format='JPEG') Note: I added the image_path function just for context and … -
Connecting Django Group models to other, non-user, models
I want to connect a model object with a group object in Django, preferably with a one-to-one relation, so that the group object is the one referencing the model object. The reason I want to have a database level connection between the two is that the alternative would be to use a naming convention that indicates that the Group belongs to the Model, but that does not feel like a good practice. It seems that the built-in Group model does not have foreign key or one-to-one fields for this and instead one way to to do this would be to subclass the Group model, like so: from django.contrib.auth import Group from django.db import models from .models import MyModel MyCustomGroup(Group): model = models.OneToOneField(MyModel, on_delete=models.CASCADE) And then connecting the two manually. Alternatively, if I want to create MyCustomGroup immediately when a new instance of MyModel is created, I can use signals or override the save method in MyModel. My end goal is to add users who are connected to a certain MyModel object, into its respective MyCustomGroup group and designate permissions to them. Is this the right approach? What are the downsides to this? The reason I'm hesitant is that this seems …