Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Docker Postgresql
When I try to use Docker and Postgresql, I got an error. I am using pipenv with django Traceback (most recent call last): [33mweb_1 |[0m File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection [33mweb_1 |[0m self.connect() [33mweb_1 |[0m File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 195, in connect [33mweb_1 |[0m self.connection = self.get_new_connection(conn_params) [33mweb_1 |[0m File "/usr/local/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection [33mweb_1 |[0m connection = Database.connect(**conn_params) [33mweb_1 |[0m File "/usr/local/lib/python3.7/site-packages/psycopg2/__init__.py", line 126, in connect [33mweb_1 |[0m conn = _connect(dsn, connection_factory=connection_factory, **kwasync) [33mweb_1 |[0m psycopg2.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution [33mweb_1 |[0m MY docker-compose.yml version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: My Dockerfile: FROM python:3.7 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ Can you guys help me with this? PS: I'm learning the Django for Professionals book by William S. Vincent chapter 3 and then this error caught me. -
__str__ returned non-string (type NoneType) and deleting data from database
can anyone help me out with the problem am facing. Am trying to make a basic matrimony website where user can upload their profile and admin has to review it before appearing the website. first part uploading the details to database it worked fine. I could able to add, modify , and delete . when I tried to add userForeignKey module to add user automatically i started facing this error "str returned non-string (type NoneType)" and it is deleting the entire data of that profile from the data base the moment I click on edit particular profile (before opening the form with instance its deleting the entire data ) and returning this error, all the data inside is just showing null in database. i tried uninstalling the module and reverted it back to to the same position where it worked before but unfortunately i couldn't get it like before and am still facing the same issue. here is my code : MODEL: class matrimony_db(models.Model): category = ( ('MALE', 'Male'), ('FEMALE', 'Female'), ) challenge = ( ('Yes', 'Yes'), ('No', 'No'), ) ms = ( ('Single', 'Single'), ('Married', 'Married'), ('Divorced', 'Divorced'), ('widow', 'widow'), ('widower', 'widower'), ) # personal details img = models.ImageField(upload_to … -
drf swagger ui for json field
Not able to show json array fields in swagger-ui of post body parameter. I have django model with JsonField column, the column name is showing in swagger ui but not able to show inside json values. Request you to please give your suggestion. #models class Sample(models.Model): ApiUser = models.CharField(max_length=100) ApiKey = models.CharField(max_length=100) create_array = models.JSONField() UserName = models.CharField(max_length=100, blank=True, null=True) IPAddress = models.CharField(max_length=100, blank=True, null=True) #serializers class SampleSerializer(serializers.ModelSerializer): class Meta: model = Sample fields = ('ApiUser','ApiKey','create_array','UserName','IPAddress') for using above model and serializer I have following request body, { "ApiUser": "string", "ApiKey": "string", "create_array": {}, "UserName": "string", "IPAddress": "string" } but expected output is, { "ApiUser": "string", "ApiKey": "string", "create_array": [{ "name": "string", "id": "string", }], "UserName": "string", "IPAddress": "string" } -
Can one docker restart another one?
I have a series of containers inside a docker network, let me call them 'backend' (an nginx-django) and 'locator' (a pure python script). What I would like to achive is that, via a web request to the 'backend' docker, achive a restart of the 'locator' module. Our current approach was to try to invoke, inside the backend, a bash console to issue a sudo docker-compose restart locator but we have several permission problems. Is there a proper way to manage, from inside one docker (in our case, 'backend') the other dockers form the network as we would do with the docker-compose commands? Our dockers are managed via a docker-compose.yml file that looks as follows: version: "3" services: locator: container_name: base-location image: registry.gitlab.com/our-group/our-locator:base-location volumes: - ./configs:/configs - ./logs/locator:/configs/logs - ./sniffing:/app/sniffing ports: - "5000:5000" - "3788:3788" - "3787:80" networks: - app_network depends_on: - backend restart: always backend: container_name: backend environment: - prometheus_multiproc_dir=/dev/shm image: registry.gitlab.com/our-group/our-backend/backend:develop_fase1 volumes: - ./configs:/configs - ./logs/backend:/app/logs - ./media:/app/media ports: - "8000:80" networks: - app_network restart: always networks: app_network: Thanks for your time. -
django project deployed on AWS using postgres - how to create a database
I have a django project that I deployed on AWS using the awsebcli. I need to provision a database (postgres) and once the enviroment is deployed I create from the console a database I would like to automate this process and I tried a config file so I tried adding this to my django.config file inside the .ebextensions folder of my project: aws:rds:dbinstance: DBAllocatedStorage: '5' DBDeletionPolicy: Delete DBEngine: postgres DBEngineVersion: 10.17 DBInstanceClass: db.t2.micro DBPassword: PASSWORD_HERE DBUser: USERNAME_HERE MultiAZDatabase: false But in this way the database is not created. I have to created it from the console and then pass as enviromental variables using the terminal (eb setenv) the endpoint of the database and other parameters. Is there a way to solve this and automate the deployment? -
Django does not display block content
Hello my block content does not work. My directory looks like this: /first_page /templates /first_page /landingPage.html /base.html This is my base.html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Text {% block content %} {% endblock %} </body> </html> this is my landingPage.html file {% extends "base.html" %} {% block content %} Hello StackOverflow! {% endblock %} Did I forget to include something? Do I have to change something in the settings? I will just "text" but not "Hello StackOverflow!" -
django block not showing
I want to add a navbar, messages and the content to the base.html, is this the right way to do it? I also want the profile to be as an extension of navbar so when you hover on profile buttton from navbar profile pops up. For now, I cannot see the navbar with block, but it work with include. base.html {% block nav %}' {% endblock nav%} {% block messages %} {% endblock messages %} {% block content %} {% endblock content %} navbar.html, should I use here include profile or a profile block? {% extends 'app/base.html' %} {% block nav%} // some more code here.. <li class="nav-item dropdown position-static"> <a class="nav-link dropdown-toggle" href="#" id="dropdown04" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Profile</a> <div class="dropdown-menu p-4" aria-labelledby="dropdown04"> {% include 'users/profile.html' %} </div> </li> {% endblock nav%} messages.html {% extends 'app/base.html' %} {% block messages %} {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> <div class="swal2-icon swal2-error swal2-animate-error-icon" style="display: flex;"><span class="swal2-x-mark"><span class="swal2-x-mark-line-left"></span><span class="swal2-x-mark-line-right"></span></span> </div> {% endfor %} {% endif %} {% endblock messages %} -
How can I return default value in django-parler if content is not filled in other langauges?
I am facing error in djagno admin. I am using django-parler package for multilangauge content and i18. For example if django admin language (i18) is in 'uz' language and content in django parler multi language content is not filled in uz, then djagno throws error that 'there is no translation for uz langauge' How can I return default value if content in specific langauge is not filled in django-parler -
How can I set token in header and redirect the user to an external url in django
I am developing an application where I need to set an token in the header and the redirect the user to another url and at receiver end I need to get the token from the request and then do some processing to display user specific data. what is the optimize way to do it functional based views -
django redirect to different view/page if permission denied
Hej! I have a view where contact details are rendered. The goal is to have some users who are allowed to see all details ('A') and some who only can see for example the name ('B'). Therefore I have two serializers in my model and two views (one for each serializer). The users are divided in two groups. The @user_passes_test does work so only the one in group 'A' are able to get into the view with the details. I want the ones which are in group 'B' to be redirected automatically to the view/page where the details are minimized. Any idea how to achieve that? I've got: # views.py def contacts_check(user): return user.groups.filter(name="Contacts = True").exists() @login_required @user_passes_test(contacts_check) def contacts(request): . . . @login_required def contacts_small(request): . . . # urls.py app_name = "app" urlpatterns = [ path("contacts", contacts, name="contacts"), path("contacts2", contacts_small, name='contacts2') ] I tried: @user_passes_test(contacts_check, login_url='contacts') but both user groups are directed to the url 'contacts' with the full view. ('B' gets an error that the user has no access). Same when login_url='contacts2'. I also tried: def sees_contacts(self): if str(self.user.groups.filter) == 'Contacts = True': return True else: return False con_login_required = user_passes_test(lambda u: True if u.sees_individuals else False, … -
How can I get space consumed by a queryset using Postgres
Suppose I make a query like - SELECT * FROM table_name WHERE condition I want to know how much disk space this queryset has consumed. -
Pycharm is not recognizing db.sqlite3 file
I am learning django and while practicing i came across a db.sqlite3 file that pycharm was not recognizing. I dragged and dropped it in db browser sqllite and i got an error "no database file opened". So what should i do? Can anyone help? If you want a clear idea of what i was doing please refer to last section(i.e project 3) of the video: https://www.youtube.com/watch?v=_uQrJ0TkZlc&ab_channel=ProgrammingwithMosh -
Django, Openpyxl: column widths are returning strange values
inside my app I'm creating a simple workbook and -sheet! Afterwards I'm iterating through a dictionary to adjust the columns width and the rows height. functions.py def create_workbook(): dict_col_width = { 'A': 2.22, 'B': 0.5, 'C': 2.33, 'D': 2.89, } dict_row_height = { 1: 44.4, 2: 9.9, 3: 15.6, 4: 85.2, } wb = Workbook() ws = wb.active ws.title = "Some title" for key, value in dict_col_width.items(): ws.column_dimensions[key].width = value for key, value in dict_row_height.items(): ws.row_dimensions[key].height = value return wb views.py ... wb = create_workbook() file_text = "some_file_name" response = HttpResponse(content=save_virtual_workbook(wb), content_type='application/ms-excel') response['Content-Disposition'] = f'attachment; filename={file_text}.xlsx' return response My problem is, that after downloading and opening the file, it seems the column widths have been created randomly. I've also tested the column width with the numbers 1 to 4 and these were the results: ws.column_dimensions[...].width = 1 --> results in a width of 0.56 ws.column_dimensions[...].width = 2 --> results in a width of 1.22 ws.column_dimensions[...].width = 3 --> results in a width of 2.22 ws.column_dimensions[...].width = 4 --> results in a width of 3.22 Strangely enough the rows were working perfectly fine! I've adjusted the column width in other programs before and this error(?) never occurred before! Does someone know … -
Django: Reproducing Migrations in Test Environment
Issue Background My development version is continuously developing with it's own database. I will makemigrations and migrate numerous times and evolve the local db. I will then push my changes on GIT once I feel the version is ready for the Test Environment. I will pull from the master and begin working on making the same migrations for the Test Environment (Has it's own DB). Issue As the code on the development version is being continuously developed (forms, views etc.) they become dependent on the models.py and database structure (imports and model usage). Therefore, when I attempt to makemigrations on the test environment by loads of dependency errors will throw up where I have referenced the new models in forms.py, views.py. For example: >>> python manage.py makemigrations File "C:\Users\<user>\<project>\<app>\forms.py", line 101, in UpdateCanisterForm choices=queryset_to_choice(CellModel.objects.all()), File "C:\Users\<user>\<project>\<app>\forms.py", line 34, in queryset_to_choice return [(x.id, x.__str__) for x in queryset] File "C:\Users\<user>\anaconda3\lib\site-packages\django\db\models\query.py", line 287, in __iter__ self._fetch_all() [...] django.db.utils.OperationalError: (1054, "Unknown column '<app>.site_id' in 'field list'") Note: <> replaced to maintain privacy Current Workaround My current work around is to comment out all the newly referenced fields until the code is happy with it's dependencies and I can migrate. What I want I'd … -
Create user in production or in local host for django
I don't know if this is a newbie question. But basically, I have website hosted on Pythonanywhere. When I want to make changes, the normal workflow is to make changes locally -> commit and push changes to github -> pull changes to pythonanywhere(PA) console and migrate. At the moment, I create accounts for my users manually and an email is then automatically sent to them with a link to set their own password. I do this like this. uid = urlsafe_base64_encode(force_bytes(user.pk)) token = default_token_generator.make_token(user) reset_view = reverse('password_reset_confirm', args=[uid, token]) url = request.build_absolute_uri( reset_view ) set_password_form = PasswordResetForm({'email':email}) assert set_password_form.is_valid() set_password_form.save( request=request, from_email="email", subject_template_name='accounts/welcome_email_subject.txt', email_template_name="accounts/welcome_email_template.html", html_email_template_name="accounts/welcome_email_template.html", extra_email_context = {'url':url , 'username':username,"name":name} ) I recently just realized that the domain of the generated password reset link depends on where I created the user account from. So if i created the user on localhost, the domain will be 127.0. 0.0 but if I created the account in Pythonanywhere, the domain will be mywebsite.com. Say if I decided to create an account on local server. the domain will be localhost so if I closed my computer before the user clicked on the link, they won't be able to set their password as the server … -
ERROR malformed node or string: <_ast.Call object at 0x7fcd19516d90> in django
I am trying to run a function on cluster after every 15 mins. But I am getting an error- The function is - def printer_function(): print("worked") reference for this function is - bbb_api.helper_lib.helper.stream_killer and I have scheduled it using on admin. but I am getting an error- ERROR malformed node or string: <_ast.Call object at 0x7fcd19516d90> can anyone help me understand this issue ? -
Django: Upload multiple directory of images at once
In my Django project, I want to upload bulk images for products from a directory of directories. Each directory is named after SKU for a product. There may or may not be multiple images inside each directory. How can I achieve this functionality? My Models: class Product(models.Model): sku = models.CharField('SKU', max_length = 200) name = models.CharField('Name', max_length = 1000) price = models.CharField('Price', max_length = 200) quantity = models.CharField('Quantity', max_length = 200) class Meta: verbose_name = 'Product' verbose_name_plural = 'Products' def __str__(self): return self.name class Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='product_image') image = models.ImageField(upload_to='images/') class Meta: verbose_name = 'Image' verbose_name_plural = 'Images' def __str__(self): return str(self.image) I can upload bulk products using the below CSV. There are multiple images inside each SKU folder below. I want to upload the images from the folders at once and link them with their respective SKUs. How can I achieve that? Any guidance will be much appreciated. NB: I can upload a single image for a product. If we want to upload thousands of products and their related images, uploading a single image is not a feasible solution. -
how to restrict pages in Django? if "@login required(login_url='login')" does not work
I'm working on this signup-login project in Django and i want to restrict home page.. but for some reason this code is not working for me.. can you tell me why? and is there any other way to restrict pages in Django? @login_required(login_url='login') views.py @login_required(login_url='login') def index(request): all_members = {} return render(request, "HTML/index.html",{'Members': all_members}) -
Memcached warn with django "Select No error"
I'm using django with memcached store realtime data maybe reset key-value per 1min , however sometimes memcached will crash with problem "[warn] select: No error", and then django will miss getting data from memcached. how can i fix it? enter image description here -
*_set attributes on models from different Apps
I have two models defined in different Apps, related by a Many to Many relationship: #App 1, models.py class Parent(models.Model): name=models.CharField(max_lenght=10) #App2, models.py from App1.models import Parent class Child(models.Model): parents = models.ManyToManyField( to = Parent, blank = True, default = None, related_name = 'padres' ) I would like to access the Child element from the Parent Model. When Models are in the same app, you can just do child_set, but in this case, it is not defined. Is there anyway to do it? I can't define the M2M relationship in Parent because I'm importing other models from App1 in App2, and doing so would lead to a circular importing. -
Celery unit test retrying
I am currently writing unit tests for my celery tasks and would like to test that my task is being retried. Note: ALWAYS_EAGER is set to True in test settings @app.shared_task(bind=True, soft_time_limit=600, autoretry_for=(Exception,), retry_kwargs={'max_retries': 3}, retry_backoff=3) def my_task(self, obj_pk): try: # ... function_call_that_can_raise_exception() except Exception as exc: last_try = self.request.retries >= self.retry_kwargs["max_retries"] if last_try: # .... else: # ... raise_with_context(exc) I can test my last run by mocking celery.app.task.Task.request; @mock.patch("celery.app.task.Task.request") def test_my_task(self): mock_task_request.retries = 3 my_task(12) # some asserts How can I test that my task is actually retried automatically? -
Display two ModelForm class in a single Django html page
I am trying to create 2 forms and display it in a single Django HTML page. I created 2 Modelform class like this class CompanyForm(forms.ModelForm): class Meta: model = Company fields = "__all__" class ToyForm(forms.ModelForm): class Meta: model = Toy fields = "__all__" In the HTML page I am only able to embed the model = Company. How can I embed the Model = Toy in the same page, what I tried brings up the same Company Form. Here is the html code <form method="post"> {% csrf_token %} <h2> Company Form </h2> {{ form.as_p }} <input type="submit" value="Submit" /> </form> <form method="post"> {% csrf_token %} <h2> Toy Form </h2> {{ form.as_p }} <input type="submit" value="Submit" /> </form> -
Django HINT: You will need to rewrite or cast the expression./ ProgrammingError
Iam using Django i got this error wile migrate ProgrammingError at /admin/images/data/add/ column "order_data" is of type integer but expression is of type date LINE 1: ...Babies_name", "Age_name", "Images") VALUES (1234, '2021-09-0... ^ HINT: You will need to rewrite or cast the expression. Request Method: POST Request URL: http://localhost:8000/admin/images/data/add/ Django Version: 3.2.7 Exception Type: ProgrammingError Exception Value: column "order_data" is of type integer but expression is of type date LINE 1: ...Babies_name", "Age_name", "Images") VALUES (1234, '2021-09-0... ^ HINT: You will need to rewrite or cast the expression. Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py, line 84, in _execute Python Executable: C:\Users\Admin\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.7 Python Path: ['D:\vikram\Django\psi', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Wed, 08 Sep 2021 20:41:59 +0000 from django.db import models # Create your models here. class data(models.Model): order_id = models.IntegerField() order_data = models.DateField() Babies_name = models.CharField(max_length=100) Age_name = models.IntegerField() Images = models.ImageField(upload_to='photo') -
django.db.utils.IntegrityError: could not create unique index "book_still_pkey" DETAIL: Key (number)=() is duplicated
That is my 2 migration where I try to change one field 'number' But I have the error : django.db.utils.IntegrityError: could not create unique index "book_still_pkey" DETAIL: Key (number)=() is duplicated. my migrations 003: class Migration(migrations.Migration): dependencies = [ ('book', '0003_auto_20510907_1254'), ] operations = [ migrations.RemoveField( model_name='library', name='number', field=models.CharField(blank=True, editable=False, max_length=8, unique=True,), ), migrations.RemoveField( model_name='library', name='link_number', field=models.PositiveIntegerField(validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(99999999)]), ), Than I changed my field 'number' in models.py and create new migration 004: class Migration(migrations.Migration): dependencies = [ ('efish', '0004_auto_20210901_2050'), ] operations = [ migrations.RemoveField( model_name='library', name='id', ), migrations.AddField( model_name='library', name='number', field=models.CharField(blank=True, editable=False, max_length=11, primary_key=True, serialize=False), migrations.AddField( model_name='library', name='link_number', field=models.PositiveIntegerField(default='', validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator( 99999999)],preserve_default=False,), ] I think the problem in primary key!Anybode can help ???Please -
Add Pagination in Django Rest Framework
I am trying to use PageNumberPagination in DRF anf for that I have changed the settings.py file like the following: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', # 'PAGE_SIZE':10 } and views.py from rest_framework.pagination import PageNumberPagination class GrnListAPIView(generics.ListAPIView): serializer_class = GrnListSerializer pagination_class = PageNumberPagination permission_classes = (permissions.IsAuthenticated, GRNViewPermission) def get_queryset(self): return Grn.objects.all() now when I try to access the data using the URL: http://localhost:8000/grns/?page=1&page_size=10 It gives me all the data rather than returning 10 objects. It works fine when I uncomment the PAGE_SIZE but only returns 10 values per page, which is understandable as I have mentioned page_size=10 in my params but when I change it to 20 or 30 it still returns the same amount of data instead of 20 or 30 objects.