Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ignore POST value from admin inline
in django i have inlineadmin with some checkboxes, i want one of them to be ignored from saving if some condition applies. I tried modifying request.POST['mykey'] or form.data['mykey'] in save_model() of main class with request.POST._mutable = True, but django save all anyway and for form.data it say is immutable. I know i can set value for obj.mykey but how to save others and ignore one? Many many thanks to all. -
How to fix error “ERROR: Command errored out with exit status 1: python.” when trying to install djangorestframework-extensions using pip
I am trying to install djangorestframework-extensions using the command: pip install djangorestframework-extensions and it shows the error: ERROR: Command errored out with exit status 1: command: /home/anamaria/workspace/licenta/AllFest2/festivals/venv/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-r9q6vdlo/djangorestframework-extensions/setup.py'"'"'; __file__='"'"'/tmp/pip-install-r9q6vdlo/djangorestframework-extensions/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-r9q6vdlo/djangorestframework-extensions/pip-egg-info cwd: /tmp/pip-install-r9q6vdlo/djangorestframework-extensions/ Complete output (6 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-r9q6vdlo/djangorestframework-extensions/setup.py", line 48 print "You probably want to also tag the version now:" ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("You probably want to also tag the version now:")? ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. What should i do? -
User Model Customisation in Django
I want to edit the User Model in admin.py but I am not able to figure out how can I do this? Here is the Image of Admin Panel of User Model Can someone please help me? I want to add some customized fields in the User model. -
Why doesn't Django 1.7+ Migrations generate meaningful names for migration files unlike South did?
Django South used to give the migration files meaningful names by default. Example from official docs, see the file name describing what the migration is actually doing: $ ./manage.py schemamigration southtut --auto + Added field dances_whenever_able on southtut.Knight Created 0002_auto__add_field_knight_dances_whenever_able.py. You can now apply this migration with: ./manage.py migrate southtut For the contrast, modern day Django built-in Migrations mechanism generates pretty boring names like 0003_auto_20200303_1439.py. As far as I know, both South and Django Migrations system were written by the same people. Does anyone know how or why that nice feature was removed/not reimplemented? For the clarity: I'm aware that in both cases it's possible to provide the desired name manually. That's not the topic of this question. The question is about the difference in the default behavior of the two tools. -
Why my django group permissions are not working?
I added some permission in django view like this.Later I assigned some user some group (which has this permission) but some unknown reason the user is not being able to process that view even if the user has this group. What might be the reason for this ? @permission_required('dashboard.can_do_something', raise_exception=True) def some_view(..).. -
DjangoFilterConnectionField filter_fields matching dictionary saved as string in database table
So to put things in perpective, I am relatively new to django not to python Have a django app where a DjangoFilterConnectionField is passed a DjangoObjectType in class Query In this app is class ptype(DjangoObjectType): class Meta: model = tablename interfaces = (Node,) filter_fields = { 'project': ('exact', 'in',), 'app': ('exact', 'in',), 'package': ('exact', 'in',) 'extra': ...... } . . . This reads fields from 'tablename' where project, app, package and extra are CharField Question is, extra in db table is stored in dictionary form but as a string extra_filter = "{context2: b, context1:a}", ( from db table ) as seen, extra filter is a string, so being a text there is no order when matching 'extra' field from db tablename and dictionary extra_filter = {'context1': 'a', 'context2':'b'} What should come here, 'extra': ..... , so that a dictionary matches an entry from table, which has dictionary saved as string "{context2: b, context1:a}" so that irrespective of order a match is successful when it is favorable ? -
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