Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to equip a django html extension / Template extending with a view?
i want a Searchfield in in my Navigation Bar. The navigation bar is integrated via {% include 'includes/navbar.html' %} in the base.html. I use a SearchForm for the Searchfield and it is displayed well on my landingpage home.html If i start the Server the it looks like this: However the Forrm() is only displayed because it is in my myapp / view.py for my landingpage. def home(request): form = SearchForm() ... return render(request, 'home.html', context) So if i click on Company, no form will show up because it´s not in my view. But i don´t want to render on every single view or Page the SearchForm() because the navbar.html is an extension loaded in my base.html and will be always shown. So for every new page i have to include the form in the navbar: def newpage(request): form = SearchForm() ... return render(request, 'company / newpage.html', context) The Question is how to equip the navbar.html with a SearchForm()? It´s not an app with it´s own views, it´s just a template. Maybe is should write a own Navbar app? myapp ├── myapp │ └── views.py ├── media ├── static ├── templates │ ├── includes │ │ └── navbar.html │ ├── base.html … -
Static Files issue between local environment and aws
When deploying to AWS, I am having issues getting static files to load from different apps, also the admin styling is lost in AWS. Below what I list for locally is how it was working previously, then below that are the changes I made to get it to work in aws, though now some of the .css files are loading empty on my local environment when running it as it should be for AWS. Also if I try and leave STATICFILES_DIRS and have STATIC_ROOT, I get an error. When running locally I need settings.py to contain: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), os.path.join(BASE_DIR, "Reporting/static/Reporting"), os.path.join(BASE_DIR, "Organization/static/Organization") ] When running in aws I need Settings.py: STATIC_ROOT = os.path.join(BASE_DIR, "static") # ADDED for AWS STATIC_URL = '/static/' ebextentions: 02_collectstatic: command: "python manage.py collectstatic --noinput" leader_only: true Any assistance will be greatly appreciated. -
Django migration - seed database while defining model
I'm on Django 2.1 and am trying to create a db table with seeded/default values in one go. Django has good documentation on how to do a 'data migration' - https://docs.djangoproject.com/en/2.2/topics/migrations/#data-migrations - This could be used to add the data I need to the table. I could do two migrations: 1) Regular migration Defines the model/table and 2) Data migration populates the data. Right now, I have to do it in two steps because the table doesn't exist until after the first migration has completed. Is there any way to do it in one shot? -
Docker-compose build give error during mysql setup
I was trying to dockerize my existing django project, I read a lot of blogs about it, I was taking a reference of https://medium.com/@minghz42/docker-setup-for-django-on-mysql-1f063c9d16a0. my docker-compose.yml version: '3' services: db: image: mysql:5.6.45 ports: - '3306:3306' environment: MYSQL_DATABASE: 'new11_uat' MYSQL_USER: 'rootd' MYSQL_PASSWORD: 'AKSHATGUPTa' MYSQL_ROOT_PASSWORD: 'AKSHATGUPTa' web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Dockerfile FROM python:3.5-alpine RUN apk add --update \ build-base \ gcc \ libc-dev \ libxml2-dev \ libxslt-dev \ mysql-dev \ musl-dev \ linux-headers \ mariadb-dev \ pcre-dev \ mysql \ mysql-client \ python3 \ python3-dev \ py-pip \ && rm -rf /var/cache/apk/* RUN pip install mysqlclient RUN mkdir /code WORKDIR /code COPY requirements_all.txt /code/ RUN pip install --no-cache-dir -r requirements_all.txt COPY . /code/ settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': 'db', 'PORT': 3306, 'OPTIONS' : { "init_command": "SET foreign_key_checks = 0;", }, } } But when I tried sudo docker-compose up, somehow there is a problem in mysql setup, I already tried to change the version of mysql but same problem db_1 | Initializing database db_1 | 2019-08-07 16:29:19 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp … -
How to filter cascading errors from Django log?
I am using django-pipeline to package static assets in my Django project. Currently there is a bug in django-pipeline that causes lots of VariableDoesNotExist errors. When this occurs, you will see a set of cascading errors in Django's default.log file like the following: [05/Aug/2019 23:18:24] DEBUG [django.template:925] Exception while resolving variable 'media' in template 'pipeline/css.html'. Traceback (most recent call last): File "/srv/https/example.com/venvs/1d91509e90bdc90520749a9ade72dbcc9dd16f27/lib/python3.5/site-packages/django/template/base.py", line 882, in _resolve_lookup current = current[bit] File "/srv/https/example.com/venvs/1d91509e90bdc90520749a9ade72dbcc9dd16f27/lib/python3.5/site-packages/django/template/context.py", line 87, in __getitem__ raise KeyError(key) KeyError: 'media' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/srv/https/example.com/venvs/1d91509e90bdc90520749a9ade72dbcc9dd16f27/lib/python3.5/site-packages/django/template/base.py", line 888, in _resolve_lookup if isinstance(current, BaseContext) and getattr(type(current), bit): AttributeError: type object 'Context' has no attribute 'media' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/srv/https/example.com/venvs/1d91509e90bdc90520749a9ade72dbcc9dd16f27/lib/python3.5/site-packages/django/template/base.py", line 896, in _resolve_lookup current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'media' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/srv/https/example.com/venvs/1d91509e90bdc90520749a9ade72dbcc9dd16f27/lib/python3.5/site-packages/django/template/base.py", line 903, in _resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [media] in "[{'False': False, 'None': None, 'True': True}, {'url': 'https://fs00.example.com/static/css/example.479c98677380.css', 'type': 'text/css'}]" Is there any way to filter out these errors such that when the … -
how to pass attr to forms.CharField
I want to pass some Html attr to a form field generated by crispy I try to this code in django 2.2.3 class AddForm(forms.Form): todo = forms.CharField(max_length=128, attrs={'placeholder':'What do you want to do?'}) but I got an error from .forms import AddForm File "C:\Users\HP\django_project\todo\forms.py", line 4, in <module> class AddForm(forms.Form): File "C:\Users\HP\django_project\todo\forms.py", line 5, in AddForm todo = forms.CharField(max_length=128, attrs={'placeholder':'What do you want to do?'}) File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\fields.py", line 214, in __init__ super().__init__(**kwargs) TypeError: __init__() got an unexpected keyword argument 'attrs' -
Creating a Rest API to search particular item over list of items
I have a list of medicine stored in the SQL database. And I want to create an API using Django REST Framework that could return a medicine that matches my search else return the entire medicine list. I do not want to make a GET request with a search query parameter but a POST request with medicine name as the key. Kindly suggest a way to do it? -
python django pass post request data into dictionary
There is a POST request that sends data to django. python 3.7 if request.method=="POST": print(request.data) this prints out <QueryDict: {'file_id': ['2019_08_07_12_17_44.943792.csv'], 'HouseNumber': [''], 'Street': ['Address'], 'Borough': ['Boro'], 'ZipCode': ['Zip']}> for this file submission. I need to turn this querydict into a python dictionary. How do I accomplish this? -
How do I modify the web I deployed?
I finished my django project and deployed on digital ocean. (Followed a youtube video blindly) my question is how do I modify the web now? what I thought was make change on my local and do git push then on my ssh do git pull. is it this easy? what happened to db then? I'm using postgresql. am I doing it wrong? -
Html form on submit doesnot redirect to url in form action
It is a really simple thing. I am not sure why it is not working. So basically an html form which has a get attribute should redirect me to the url specified in the action = 'url'. But when I submit the form in my browser, instead of redirecting me to http://127.0.0.1:8000/blog/articles the browser stays on the home page. So after submitting, I should be on the page http://127.0.0.1:8000/blog/articles?q=tesla. Instead I stay on the page http://127.0.0.1:8000/q=tesla. I have already tried many alternatives such as replacing the django templating {% url %} tag with the actual url value 'http://127.0.0.1:8000/blog/articles'. None of these work. Is there something wrong with Django and html submit forms? <form action="{% url 'blog-articles' %}" method='GET'> <input class="search_input" type="text" name="q" placeholder="Search..." id ='textBoxSearch'/> <button type="submit" class="search_icon fabutton" id = 'btnSearch' value="Register"><i class="fas fa-search"></i></button> </form> Expected:http://127.0.0.1:8000/blog/articles?q=tesla Actual:http://127.0.0.1:8000/q=tesla -
Django management command does not show logs of my library
This question is a simpler version of this 4 years old question without answer Django management command doesn't show logging output from python library: I have a command: class Command(BaseCommand): def handle(self, *args, **options): ... MyParser(data) And in MyParser: logger = logging.getLogger(__name__) Class MyParser: def __init__(self, data): logger.info('hello') Why the logger does not display to stdout when I run the command? With a print it is OK but I need a logger PS: I tried this but it does not change anything from parser import logger root_logger = logger root_logger.setLevel(logging.INFO) MyParser(data) -
Creating a django api to read a file content and display on Angular frontend
I need to create a django api which will read the contents of a file and display it on the angular frontend all in a bash script This is on a centos7 machine and the file to be read is on a different centos 7 machine I expect the contents of that file to be displayed on the Angular Frontend -
I cant migrate and run my server successfully in django
I am getting an error whenever i want to migrate and run my server in django. File "C:\Program Files\Python37\lib\site-packages\django\db\backends\base\base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "C:\Program Files\Python37\lib\site-packages\django\db\backends\mysql\base.py", line 227, in get_new_connection return Database.connect(**conn_params) -
Django rest api to handle csv data
I am relatively new to Django and DRF, however I have managed to implement DRF and its working successfully with the default json content negotiation. Now I have been given a task where the api will receive some telemetry data in csv format without headers. The headers shall be hard coded as it won't change. Example, ads123,0,12.5,0,1,23,abcd Now I need to develop a rest api that can accept csv data, save it in a postgres/sqlite db and return the response in csv. I have searched the net have been unable to find a suitable solution. I found djangorestframework_csv but then i believe it needs a header in its csv data from what I saw. Kindly suggest if possible with an example. -
Data migration to replace instances of a word in a TextField?
I am writing a data migration to go through some general templates used to send notifications with the goal of changing all instances of 'word1' to 'word2'. 'word1' can occur in both the name of the template as well as the body. Currently, there is only one template with 'word1' in the name, so I am able to change that one easily with an if statement that grabs that exact name and replaces it with the desired name. The issue I am running into is swapping 'word1' with 'word2' when it appears in the body of a template. An additional note to make is that the occurrences of 'word1' in the body are independent entirely from the occurrences in the name. So far, I've tried using an if statement with a_notification.body.contains('word1') in my for loop to find which notifications contain that word. I've also tried splitting up the body into a list of words, splitting the textfield by space characters, and then using a for loop to check each individual word to see if it is equal to 'word1'. Currently, I am trying to use .replace() to find the instance and replace it with the desired word. Migration file: #Generated … -
Using Python 3.7 contextvars to pass state between Django views
I'm building a single database/shared schema multi-tenant application using Django 2.2 and Python 3.7. I'm attempting to use the new contextvars api to share the tenant state (an Organization) between views. I'm setting the state in a custom middleware like this: # tenant_middleware.py from organization.models import Organization import contextvars import tenant.models as tenant_model tenant = contextvars.ContextVar('tenant', default=None) class TenantMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) user = request.user if user.is_authenticated: organization = Organization.objects.get(organizationuser__is_current_organization=True, organizationuser__user=user) tenant_object = tenant_model.Tenant.objects.get(organization=organization) tenant.set(tenant_object) return response I'm using this state by having my app's models inherit from a TenantAwareModel like this: # tenant_models.py from django.contrib.auth import get_user_model from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from organization.models import Organization from tenant_middleware import tenant User = get_user_model() class TenantManager(models.Manager): def get_queryset(self, *args, **kwargs): tenant_object = tenant.get() if tenant_object: return super(TenantManager, self).get_queryset(*args, **kwargs).filter(tenant=tenant_object) else: return None @receiver(pre_save) def pre_save_callback(sender, instance, **kwargs): tenant_object = tenant.get() instance.tenant = tenant_object class Tenant(models.Model): organization = models.ForeignKey(Organization, null=False, on_delete=models.CASCADE) def __str__(self): return self.organization.name class TenantAwareModel(models.Model): tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, related_name='%(app_label)s_%(class)s_related', related_query_name='%(app_label)s_%(class)ss') objects = models.Manager() tenant_objects = TenantManager() class Meta: abstract = True In my application the business logic can then retrieve querysets using … -
How to fix this error: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}`
I have tried many things to solve my problem but I can't resolve it. I want to give user details when I give the token but I get this error: ##AssertionError at /api/token/get HyperlinkedIdentityField requires the request in the serializer context. Add context={'request': request} when instantiating the serializer.## Here the code in views.py class GetUserInfo(RetrieveUpdateAPIView): # permission_classes = (IsAuthenticated,) serializer_class = UserSerializer def get(self, request, *args, **kwargs): serializer = self.serializer_class(request.user) # serializer to handle turning our `User` object into something that # can be JSONified and sent to the client. return Response({"user": serializer.data}, status=status.HTTP_200_OK) Here the code in serializers.py lass UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('title', 'dob', 'address', 'country', 'city', 'zip', 'photo','director','manager','collaborator') class UserSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer(required=True) class Meta: model = User fields = ('url', 'email', 'first_name', 'last_name', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() UserProfile.objects.create(user=user, **profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.email = validated_data.get('email', instance.email) instance.save() profile.title = profile_data.get('title', profile.title) profile.dob = profile_data.get('dob', profile.dob) profile.address = profile_data.get('address', profile.address) profile.country = profile_data.get('country', profile.country) profile.city = profile_data.get('city', profile.city) profile.zip = profile_data.get('zip', profile.zip) profile.photo = profile_data.get('photo', profile.photo) director … -
Django migration error - ValueError: Invalid model reference 'apps.auth.Permission'
When I run python manage.py makemigrations users I get ValueError: Invalid model reference 'apps.auth.Permission'. String model references must be of the form 'app_label.ModelName'. my django file structure is . ├── README.md ├── __init__.py ├── apps │ └── users │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── models.py │ ├── tests.py │ └── views.py ├── manage.py ├── siteconfig │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py └── virtualenv some relevant variables from settings.py are settings.py PROJECT_ROOT = os.path.dirname(__file__) sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps')) AUTH_USER_MODEL = 'users.CustomUser' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.users.apps.UsersConfig', 'rest_framework', ] users/models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext as _ class CustomUser(AbstractUser): kindle_email_address = models.EmailField(_('kindle email address')) users/apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'apps.users' The full stack trace is: Traceback (most recent call last): File "/virtualenv/lib/python3.7/site-packages/django/db/models/utils.py", line 11, in make_model_tuple app_label, model_name = model.split(".") ValueError: too many values to unpack (expected 2) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/virtualenv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, … -
how to save object of PIL.Image.Image in django ImageField ? Django image processing?
I'm working on a Django project where users can upload images and it will be processed by a function made by a friend of mine. first, the function returned the image in the same path as the uploaded image with changing the filename and this wouldn't save the model field as the model has it's own file_path so I asked my friend to make the function return just an image and now the function returns object of PIL.Image.Image but whenever I call the save I get errors like object has no attribute '_committed' so when I searched, I stumbled across answers regarding BytesIO and saving it in in-memmory blob You can use a BytesIO to save the Pillow file to an in-memory blob. Then create a File object and pass that to your model instance ImageField's save method. but is this the best practice? and how can I imply this in my situation? btw the processing function is named main models.py class UploadedImages(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images') pre_analysed = models.ImageField(upload_to = user_directory_path , verbose_name = 'Image') class Processed(models.Model): uploaded_image = models.ForeignKey(UploadedImages,on_delete=models.CASCADE,related_name='processed') analysedimage = models.ImageField(upload_to=analyses_directory_path, verbose_name='analysed Image', blank=True) views.py def AnalysedDetails(request,pk=None): Uimage = get_object_or_404(models.UploadedImages,pk=pk) analysed = models.Processed(uploaded_image=Uimage,analysedimage=main(Uimage.pre_analysed.path)) analysed.analysedimage = main(Uimage.pre_analysed.path) analysed.analysedimage.save() return … -
Django AuthUserAdmin get_form override method being ignored
I want to override the get_form method for the AuthUserAdmin class with something like this (taken from https://realpython.com/manage-users-in-django-admin/): class AuthUserAdmin(admin.ModelAdmin): list_display = ('id', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_superuser', 'is_active', 'last_login') def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) is_superuser = request.user.is_superuser disabled_fields = set() # type: Set[str] if not is_superuser: disabled_fields |= { 'username', 'is_superuser', } for f in disabled_fields: if f in form.base_fields: form.base_fields[f].disabled = True return form However, the method is never called when the user opens the change form. -
Django: trigger SweetAlert2 in the redirect
I am new to JS, and I want to implement a dialog message with SweetAlert2 for 2 sec. A the moment I'm triggering the message with the submit button which is not great. I want to know how to trigger it after the redirection. views.py def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) return redirect('product_tree:index') else: form = PasswordChangeForm(request.user) return render(request, 'accounts/change_password.html', { 'form': form }) change_password.html [...] <button type="submit" class="btn btn-success" id="ResetPassword">Save</button> [...] alerts.js $('#ResetPassword').click(function(){ Swal.fire({ position: 'top-end', type: 'success', text: 'New password saved!', showConfirmButton: false, timer: 2000 }) }); -
How can i add depth=1 to BaseSerializer
ModelSerializer have a depth in Meta class GeneralSerializer(serializers.ModelSerializer): class Meta: model = None depth = 2 fields = '__all__' any alternative in BaseSerializer? -
Avoiding function calls in 'where' clause of sql queries generated by django
The Django generating sql queries with function calls in where clause like below, when using Django queries for search or any other purposes. SELECT COUNT(*) AS "_count" FROM "products_product" INNER JOIN "products_productmeta" ON ("products_product"."meta_id" = "products_productmeta"."id") WHERE ((NOT ("products_product"."archived" = true) AND "products_product"."owner_id" = 1281 AND UPPER(UNACCENT("products_product"."sku")::text) LIKE '%' || UPPER(REPLACE(REPLACE(REPLACE((UNACCENT('octavi')), '\', '\'), '%', '\%'), '', '_')) || '%') OR (NOT ("productsproduct"."archived" = true) AND "products_product"."owner_id" = 1281 AND UPPER(UNACCENT("products_productmeta"."name")::text) LIKE '%' || UPPER(REPLACE(REPLACE(REPLACE((UNACCENT('octavi')), '\', '\'), '%', '\%'), '', '_')) || '%') ) Response time is taking too long with these type of queries because of whole data sets are passing through the function calls. Is there any way to avoid those function calls such as UPPER, REPLACE etc... in where clause of sql generated by django? Is writing raw sql queries the only option? -
Django 2.2 upgrade - mongoengine query performance
We are trying to upgrade from Django 2.1.11 to 2.2.4. During the upgrade we noticed a significant performance drop relating to queries made through the mongoengine library (http://mongoengine.org/) We did some profiling with pyspy (https://github.com/benfred/py-spy) and noticed the control flow is significantly different and there are lots of extra function calls relating to pagination. I can't find anything in the release notes for Django 2.2 (https://docs.djangoproject.com/en/2.2/releases/2.2/) that suggests why we might be getting the problem. Any help is much appreciated. We have tried doing some profiling with pyspy and some other tools and we tried different minor versions but it seems to broken in all Django 2.2 versions. def get_context_data(self, **kwargs): ctx = super(BaseOverview, self).get_context_data(**kwargs) ctx['result_template_name'] = self.result_template_name ctx['action_form'] = self.action_form ctx['page_size_form'] = self.page_size_form ctx['submitted'] = self.submitted ctx['model'] = self.model ctx['paginate'] = self.paginate_by results = ctx[self.context_object_name] if not isinstance(results, list): # Need to evaluate the queryset, so attached data remains set results = results.select_related(max_depth=self.select_depth) self.attach(results, self.request.session['environment']) # assert len(results) <= self.paginate_by ctx[self.context_object_name] = results return ctx Where results is a mongoengine Document class instance pyspy output -
Installed Django and ran now it says command not found
I am new to python and Django I have installed Python 3.7 and Django on MacOS 10.14 followed online tutorials I created folder on Desktop called Development and in that i have test, polls folder. ran python manage.py runserver open browser 127.0.0.0:8000 it worked. Then I was trying sample project from Django website it did not work so next day I want to troubleshoot my code. I cd to development folder ran python manage.py runserver keep saying command not found. I could not find answers online. My question do i have to create virtualenv every time I want to open existing Django project? how do I open existing project please if you can give me step by step that would be great.