Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
docker-compose up error for django and mysql
I am trying to configure Django and MySql application with Docker containers. For Django I am using python:3.7-slim image and for MySql mysql:5.6. When I run docker-compose up it returns an error stated below - ERROR: for app_mysql_db_1 Cannot start service mysql_db: driver failed programming external connectivity on endpoint app_mysql_db_1 (c647d4793a198af2c09cc52d08191fb2cd984025ad0a61434ad1577d9dcccebe): Error starting userland proxy: listen tcp 0.0.0.0:3306: bind: address already in use I run command docker ps -a to check docker status and found that mysql container was created but the python container status was exited. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 7d91795e0bae mysql:5.6 "docker-entrypoint.s…" 15 seconds ago Created app_mysql_db_1 fa0419ad0f21 e0bf94710555 "/bin/sh -c 'adduser…" 2 minutes ago Exited (1) 2 minutes ago pedantic_faraday can someone rewrite or suggest the modification for the configurations. Dockerfile FROM python:3.7-slim ENV PYTHONUNBUFFERED 1 RUN apt-get update RUN apt-get install python3-dev default-libmysqlclient-dev gcc -y COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY . /app docker-compose.yaml version: "3" services: eitan-application: restart: always build: context: . ports: - "8000:8000" volumes: - ./eitan:/app command: > sh -c "python3 manage.py runserver 0.0.0.0:8000 && python3 manage.py makemigrations && python3 manage.py migrate" depends_on: - mysql_db mysql_db: image: mysql:5.6 command: mysqld --default-authentication-plugin=mysql_native_password … -
How to add a day to date field value in Django views
I have the following code: my_date = request.POST.get('to_date') to_date = datetime.strptime(my_date,"%Y-%m-%d") + timedelta(days=1) This however gives me an error: strptime() argument 1 must be str, not datetime.datetime. So I tried this: my_date = request.POST.get('to_date') to_date = my_date + timedelta(days=1) This treats the my_date value as a string and gives the error: can only concatenate str (not "datetime.timedelta") to str. If I print type(my_date) it says <class 'str'>. Can someone please advise on how to handle this? -
Django queryset to filter objects with identical manytomany field
I've got a model like this. class Component(models.Model): options = models.ManyToManyField('prices.Option') period = models.IntegerField() I need to select all components with same period and same options as one component cmp. This queryset doesn't work. similar_components = Component.objects.filter(period=cmp.period, options=cmp.options) I can't find a way to make a queryset baset on this manytomany field options. -
cleaned_data() returns empty objects, when I try to upload multiple images in Django
models.py: class Object(PolymorphicModel): author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE) title = models.CharField(max_length=300) city = models.ForeignKey(City, on_delete=models.CASCADE) address = models.CharField(max_length=300) phone = models.CharField(max_length=20, default='') email = models.CharField(max_length=100, default='') site = models.CharField(max_length=100, default='') facebook = models.CharField(max_length=100, default='') instagram = models.CharField(max_length=100, default='') content = models.TextField() rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2) created_date = models.DateTimeField(default=timezone.now) approved_object = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) def __str__(self): return f"{self.title}" class Restaurant(Object): seats = models.IntegerField() bulgarian_kitchen = models.BooleanField(default=False) italian_kitchen = models.BooleanField(default=False) french_kitchen = models.BooleanField(default=False) category_en_name = models.CharField(max_length=100, default='restaurants') category_bg_name = models.CharField(max_length=100, default='Ресторанти') bg_name = models.CharField(max_length=100, default='Ресторант') is_garden = models.BooleanField(default=False) is_playground = models.BooleanField(default=False) class Images(models.Model): object = models.ForeignKey(Object, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='attachments', verbose_name='Image') forms.py: class RestaurantForm(forms.ModelForm): class Meta: model = Restaurant fields = [ 'title', 'content', 'city', 'address', 'phone', 'email', 'site', 'facebook', 'instagram', 'seats', 'bulgarian_kitchen', 'italian_kitchen', 'french_kitchen', 'is_garden', 'is_playground' ] class ImageForm(forms.ModelForm): image = forms.ImageField(label='Снимка') class Meta: model = Images fields = [ 'image' ] template (html): <form method="post" id="dialog_addObject_part"> {% csrf_token %} {% for hidden in postForm.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form %} <div class="fieldWrapper"> <div class="errorcode{{field.html_name}}"> {{ field.errors }} </div> {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} {{ formset.management_form … -
Django:how to set pagination as per user selected set?
Django:how to set pagination as per user selected set? -
How to migrate Enumfield values in Django properly?
Suppose we have an Enum: class MyEnum(Enum): FOO = "FOO" BAR = "BAR" BAZ = "BAZ" that is used in a field: from enumfields import EnumField class FooModel (models.Model) foo_field = EnumField( MyEnum, null=True, blank=True, default=MyEnum.FOO) Then I want to remove one of the fields in MyEnum, because I do not want value FOO in my database anymore class MyEnum(Enum): BAR = "BAR" BAZ = "BAZ" from enumfields import EnumField class FooModel (models.Model) foo_field = EnumField( MyEnum, null=True, blank=True, default=MyEnum.BAR) I need to migrate data, so my migration may look like this: def migrate_not_for_sale_to_private(apps, schema_editor): FooModel = apps.get_model("foo", "FooModel") for obj in FooModel.objects.all(): if obj.foo_field == "FOO": obj.foo_field = "BAR" obj.save() This one fails, because I changed allow values for foo_field to BAR and BAZ, and so if obj has value FOO, it blows up with not allowed value error. How one should do it properly? I could leave MyEnum values as they are, marking one as legacy, but in a long run it leads to a lot of potential legacy fields. The other way could be running raw SQL command (assume I am using PostgreSQL). -
Django Channels listening TCP/UDP
I have a GPS tracker that communicates with TCP protocol. The data will be send to web client via Websocket. I also need to persist it to database. I intent to use Django as my main framework for this. But the problem is the TCP protocol. Can django channel listen to TCP/UDP protocol?? Or should I use asyncio and then send it to django channels applications via ASGI?? -
Why save() method has another save() method with super in django model
I am creating models, where i get bit confusion about save() has another save method with super keyword, why two save() methods, appreciate for explination. from django.db import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def save(self, *args, **kwargs): do_something() super().save(*args, **kwargs) # Call the "real" save() method. do_something_else() -
How to achieve associative law in django?
I have three objects for a model A, B, C A is related to B and B is related to C How can I achieve relation from A to C in django? -
Zappa Django Rest Framework API timeout on AWS Cognito call
I'm migrating a Django Rest Framework API to lambdas, with Zappa This API is also running on an Elastic Beanstalk application and works fine there. First I got error messages while trying to connect to the database, Then I did set the lambda VPC and security groups, and it seems that this error is gone, however, any call to the authentication endpoint (that uses Cognito) results in a timeout. I know that API Gateway is hardcoded to timeout after 29s, but I don't think this endpoint should be taking that long. I've enabled X-Ray, but it doesn't say much, just that the function timed out Looking at the Cloudwatch logs I could point the moment it gets stuck 09:10:09 [DEBUG] 2020-03-04T09:10:09.326Z 2e2ba999-a6bf-42e0-a5f1-6b4c70e72981 Starting new HTTPS connection (1): cognito-idp.us-east-1.amazonaws.com:443 [DEBUG] 2020-03-04T09:10:09.326Z 2e2ba999-a6bf-42e0-a5f1-6b4c70e72981 Starting new HTTPS connection (1): cognito-idp.us-east-1.amazonaws.com:443 09:10:10 09:10:30 END RequestId: 2e2ba999-a6bf-42e0-a5f1-6b4c70e72981 END RequestId: 2e2ba999-a6bf-42e0-a5f1-6b4c70e72981 09:10:30 REPORT RequestId: 2e2ba999-a6bf-42e0-a5f1-6b4c70e72981 Duration: 30030.18 ms Billed Duration: 30000 ms Memory Size: 512 MB Max Memory Used: 141 MB Init Duration: 469.61 ms XRAY TraceId: 1-5e5f7067-d06b5ff2aaa8b9c6218f7444 SegmentId: 6ef0fb0d7de15cfe Sampled: true REPORT RequestId: 2e2ba999-a6bf-42e0-a5f1-6b4c70e72981 Duration: 30030.18 ms Billed Duration: 30000 ms Memory Size: 512 MB Max Memory Used: 141 MB Init … -
Django-multi-database-routing
I have tasks in my project as below and I need help in this : 1) I need to use 2 Databases: PostgreSQL DB and My SQL DB. 2.) Project has 2 roles Admin and User PostgreSQL has 2 database: database1, database2 My SQL has 3 database: database3, database4, database5 I need to create a django application where admin can add users and assign multiple database (database1, database2, database3, database4, database5 ) to a user and when the user is created, he should get Email for login and password(or any other way to handle this flow). When user performs login, he can see the database list, which admin assigned to him. Then user can create Product by selecting database from the List. Product should be save under selected database. There should be one page where user can see all product list with database name. Admin has one page, where he can see all user's and their product details. -
Can I run two Django Project in the same server?
I already have created one Django project in an Apache server using CentOS 7 , python3... Now I have to create another django project and I wonder if I should add this project in the same server or in a new Server . Any advise please ? -
Django, filtering mysql database
I have due_date column in DB and trying to filter rows by the value of that column. So the values in the column looks like "2020-01-20" and I am trying to filter it till year and month. NOT till Day In the function below: def retrieve(request): date = "2020-01" tasks = Task_Histories.objects.all().filter(due_date=date) serializer = InvocesSerializer(invoces, many=True) return Response(serializer.data) How can I arrange DB column value before matching it in the filter()? -
Django Failed to establish a new connection
I'm developing a project with Django. In this project, I run django on my cloud server. http://x.x.x.x:8000 I am trying to get data from a local web service. headers = {'content-type': 'application/json'} url = 'http://y.y.y.y:8090/api/jserv.ashx' params = {'action': 'ReportMethod'} data = {"user": { "userid": "xx","username": "User","status": "false","mesaj": "null","masterno": 0,"versiyon": "null"},"start": "1900-01-01T00:00:00","end": "2020-02-25T00:00:00"} r = requests.post(url, params=params, data=json.dumps(data), headers=headers) I got: HTTPConnectionPool(host='y.y.y.y', port=8090): Max retries exceeded with url: /api/jserv.ashx?action=ReportMethod (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f4649c98eb8>: Failed to establish a new connection: [Errno 110] Connection timed out',)) -
django REST framework api without using models
I'm new to django rest framework. In my project i need to send api on a request, here i'm not using model data instead i want to send a dictionary as api response which is read from external database like mongodb. how to do this? viewset code class LivedataViewSet(viewsets.ModelViewSet): queryset = LiveData.objects.all() serializer_class = LiveDataSerializer def get_queryset(self): qs = super().get_queryset() user_id = str(self.request.query_params.get('user')) if user_id: queryset = qs.filter(user=user_id) return queryset else: return qs and serializer code is class LiveDataSerializer(serializers.ModelSerializer): class Meta: model = LiveData fields = ('id', 'user', 'status') this code works but it uses model here i need same function without model. -
I want to forece change password on first login Django Rest
I have a custom User model with field is_resetpwd as a boolean field with default value True I want that to change to False when the password is changed, following is my password change view class ChangePasswordView(APIView): """ An endpoint for changing password. """ serializer_class = ChangePasswordSerializer model = User permission_classes = (IsAuthenticated,) def get_object(self, queryset=None): obj = self.request.user # print("obj", obj) return obj def post(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): # Check old password if not self.object.check_password(serializer.data.get("old_password")): return Response({"old_password": ["Wrong password."]}, status=status.HTTP_400_BAD_REQUEST) # set_password also hashes the password that the user will get self.object.set_password(serializer.data.get("new_password")) self.object.save() response = { 'message': 'Password updated successfully', } return Response(response) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) what should I add in this to change my boolean value -
Cannot Get image From Database Django Framework
I want to create a setting in admin panel which will help me to change the website logo from the admin panel. I create a model for database and it's working and uploading an image to the database + folder. but I cannot get this image to the Website template. when I'm viewing page source image SCR is empty. my Model.py class WebLogo(models.Model): Logotitle = models.CharField(max_length=50,unique=False) SiteLogo = models.ImageField(upload_to='webimages') def __str__(self): return self.Logotitle my Views.py from .models import Post,WebLogo def Display_WebLogo(request): # getting all the objects of hotel. WebsiteLogo = WebLogo.objects.all() return render((request, 'index.html',{'web_images' : WebsiteLogo})) my project Urls.py urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my Html Code <a href="index.html"><img src="{{ WebLogo.SiteLogo.url }}" class="img-fluid" alt="logo"> </a> my app url from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), ] -
500 error vs 404 error which one is more desirable?
I am a student who is studying the development of django. I have a question about 404 and 500 errors. I handle 404,500 error as 404.html and 500.html respectively. So, is there a difference between these two error events? For example, def example_post_404(request, pk): get_object_or_404(Post, id=pk) # code that may occur 404 error vs def example_post_500(request, pk): Post.objects.get(id=pk) # code that may occur 500 error Did 500 error event put more pressure on the server than 404 error event? Which code is more desirable? My code is running on AWS EC2 ubuntu-16.04 -
Python Requests - Disable SSL Verification
I have a Django app with a very large code base and so many requests been made, How can I disable python-requests SSL verifications globally as it will be impossible to add verify=False to all the places requests was used, I have tried adding REQUESTS_CA_BUNDLE=/usr/local/lib/python2.7/site-packages/certifi/cacert.pem to my environmental variables but I still get the same error Caused by SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:727)'),)) My version of requests is 2.19.1 is there a way to ignore this validation completely -
Django Connection pool to SQL backend with gunicorn
Is there currently any working solutions to enable connection pooling for SQL requests in Django, running in Gunicorn? Is there any built in functionality that can be enabled, or would I have to rely on an external project? From what I can gather there are two external modules you can install from pypi, but they don't seem to have a particularly high user base. https://pypi.org/project/django-db-connection-pool/ https://pypi.org/project/django-db-pooling/ -
I accidentally deleted the migrations folder in Django
I am using Django, and Postgre for the DB. So I was done with all the migrations, but then I accidentally deleted the migrations folder in my editor. So I did the 'python manage.py makemigrations' again in the terminal, hoping I can get the folder back, but it replied 'No changes detected.' What should I do to get the folder back? Is it wrong to just simply make migrations again? I've tried creating a new database and re-do the same process, but it still says 'No changes detected.' I very much appreciate your help. :) -
How to correctly have contrib.auth in both shared and tenant schemas
I'm trying to build multi-tenants web app using django. I'm using django-tenant-schema. I want to maintain seperate auth table for public schema and tenants schema. I need some suggestions. -
html does not send post to view
I have a submit form like: <div class="form-group"> <div class="checkbox"> <label for="id_active_state"> <div class="icheckbox_square-red checked" style="position: relative;"> <input type="checkbox" name="active_state" class="" id="id_active_state" checked=""><ins class="iCheck-helper"></ins> </div> active</label> </div> </div> <div class="form-group"> <div class="button_holder"> <button type="submit" name="submit" class="btn btn-primary" value="send"> submit </button> </div> </div> and it should be handled in view: def special_offer_edit_view(http_request): action_verbose_name = 'the_view' special_offer_id = http_request.GET.get('id') special_offer_obj = SpecialOffer.objects.filter(id=special_offer_id) for data in special_offer_obj: sp_obj = {'active_state': data.active_state} if http_request.method == 'POST': print('hi') return render(...) it raises 503 error, and does not send "POST" method and data. what is its problem? -
Hide public model from tenant admin in django
I am using Django Tenant Schema in my project. Some of my models are public and shared by all tenants and some to tenant_schema. I have registered all models from ( shared_app and tenant_app ). Suppose models public1, public2 are shared app and I have 2 registered tenant (tenant1 and tenant2). Problems I am facing: 1. when I open admin of tenant1 ( tenant1.domain.com/api/admin ) I am able to view public1 model but i am not able to view data consistently in both tenant1 and tenant2. 2. Is there a way to hide public schema in tenant admin and and only show public model in domain admin ( domain/api/admin ) -
how to put hashtag regex in ajax form method
I already did a hashtag in the base.html it is working. like if anyone type something with #something it will replace by the javascript in the html with links. It is working on the post list. so i want to work it on the comments. But the comments have ajax method that's why it is not working in the comments. can we keep them both(AJAX and Hashtag). my base.html: $(document).ready(function() { $("p").each(function(data) { var strText = $(this).html(); console.log('1. strText=', strText); var arrElems = strText.match(/@[a-zA-Z0-9]+/g); console.log('arrElems=', arrElems); $.each(arrElems, function(index, value){ strText = strText.toString().replace(value, '<a href="/user/'+value.replace('@', '')+'">'+value+'</a>'); }); console.log('2. strText=', strText); $(this).html(strText); }); }); (#the ajax method for comments) $(document).on('submit', '.comment-form', function(event){ event.preventDefault(); console.log($(this).serialize()); $("p").each(function(data) { var strText = $(this).html(); console.log('1. strText=', strText); var arrElems = strText.match(/@[a-zA-Z0-9]+/g); console.log('arrElems=', arrElems); $.each(arrElems, function(index, value){ strText = strText.toString().replace(value, '<a href="/user/'+value.replace('@', '')+'">'+value+'</a>'); }); console.log('2. strText=', strText); $(this).html(strText); }); }); $.ajax({ type: 'POST', url: $(this).attr('action'), cache: false, data: $(this).serialize(), dataType: 'Json', success: function(response) { $('.main-comment-section').html(response['form']); $('textarea').val(''); $('.reply-btn').click(function() { $(this).parent().parent().next('.replied-comments').fadeToggle() $('textarea').val(''); }); }, error: function(rs, e) { console.log(rs.responseText) }, }); }); my comments.html: <form method="post" enctype="multipart/form-data" class="comment-form" action="."> {% csrf_token %} {{ comment_form.as_p }} <input type="submit" value="submit" class="btn-btn-outline-success"> </form> <div class="container"> {{ comments.count }} comment{{ comments|pluralize }} {% …