Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to import custom fabric folder
so i have this script, that i use to log in on many servers trouhg ssh and it was runing ok on python2 /user/local/bin/a #!/usr/bin/env python # coding: utf-8 from __future__ import print_function, unicode_literals import os import sys sys.path.append("fabric_/") import fabfile if len(sys.argv) != 2: print('Usage: a <host>') sys.exit(-1) os.system('ssh root@{}'.format(fabfile.env.roledefs[sys.argv[1]][0])) but, now with python3, when i try to run the command("a client") it gives me a error the correct fabfile that has the "env" is on my project folder ruicadete/fabric_/fabfile.py i already tried to make sys.path only with the right fabfile, it worked but the it doesn't find the modules i've imported on the fabfile. what i'm doing wrong? -
Item in the array did not validate: Select a valid choice. ["Acamedic" is not one of the available choices
I am trying to use CharField with choices using postgres ArrayField. here is my code; BOOK_CATEGORY = ( ("Academic", "Academic"), ("Science Fiction", "Science Fiction"), ("For Student", "For Student"), ("Others", "Others"), ) class Book(models.Model): category = ArrayField(models.CharField(max_length=100, choices=BOOK_CATEGORY), blank=True, null=True) Here is the error I get when I try to post a value; ["Acamedic", "For Student", "Others"]; -
Elastic BeanStalk Django Error in Pipfile
This is my first time deploying on AWS Elastic BeanStalk. I have built an application https://github.com/ChristopherPHolder/dribblz and decided I should deploy it on Elastic BeanStalk so I tried to follow their tutorial on https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html I have been trying to deploy it for 2 days now but don't know what else to try. It seems like there are many questions here related to Elastic BeanStalk but not all of them have answers and non of them seem to have the same issue as me. I get this error: ERROR: ServiceError - Create environment operation is complete, but with errors. For more information, see troubleshooting documentation. And if I inspect the logs I can narrow down the error to a problem with pipenv in the pipfile. [ERROR] An error occurred during execution of command [app-deploy] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with Pipfile file with error Command /bin/sh -c /usr/bin/python3.8 -m pipenv install --skip-lock failed with error exit status 1. Stderr:Traceback (most recent call last): ... ... json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 4 column 1 (char 35) The line causing trouble seems to be verify_ssl = true However, I have tried deleting the … -
username still required o generate token even if it is removed from user model in django restframework
I'm still having this error when trying to do a post request from postman{"username":["This field is required."]}. Please note that Abstract User class was overrided to support email authentication with username = None. UserManager and UserAdmin also were overrided -
How to implement django-gssapi 0.9b3
I recently asked if anyone knew how to fix an issue I have with an Python/Django application that I integrated with IIS. The problem is that IIS buffering is overriding my use of the Django yield function to return output to the browser in real-time - my question was never answered and has been deleted. I only used IIS to front the application so that users would be made to sign-in using their windows credentials. Now I've decided to remove IIS altogether as I want my Django yield functionality back plus, I only have five users of the application - so I'm going to use the Django provided web server. To substitute the requirement for my users to logon using their windows credentials I would like to implement the python library 'django-gssapi 0.9b3' which would provides GSSAPI authentication for Django and in-turn, a transparent logon experience for my users. I would like to ask if anyone anyone has experience implementing this library to allow SSO for windows clients using Kerberos and if so, could you please share links for examples / instructions on how to get this library working with Django? I'm using Django 3.2.3 and Python 3.6.8 running on … -
Can't send email in Django Using Django Q
I am learning Django Q and to see how it works I am trying to send email. But when i am checking my gmail, email is not received( I also checked spam). It is also not showing an error. Following is the code: Settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_HOST_USER = '***@gmail.com' EMAIL_HOST_PASSWORD = '***' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' Q_CLUSTER = { 'name': 'appName', 'retry': 5, 'workers': 4, 'orm': 'default', 'workers': 8, 'recycle': 500, 'timeout': 60, 'compress': True, 'save_limit': 250, 'queue_limit': 500, 'cpu_affinity': 1, 'label': 'Django Q', 'redis': { 'host': '127.0.0.1', 'port': 6379, 'db': 0, } } View.py Following is the function which I am calling when user successfully logs in def welcome_mail(user): msg = 'Welcome to our website' # send this message right away async_task('django.core.mail.send_mail', 'Welcome', msg, 'mail@gmail.com', [user.email], fail_silently=False, ) print("Email Sent--------") # and this follow up email in one hour msg = 'Here are some tips to get you started...' schedule('django.core.mail.send_mail', 'Follow up', msg, 'mail@gmail.com', [user.email], schedule_type=Schedule.ONCE, next_run=timezone.now() + timedelta(hours=1)) -
PDF Editor Incorporated on Website through html and iframe - Image and Text
I need to incorporate a PDF editor that can directly edit the PDF's text and add images. I plan to add it to my website using tags. I have been searching forever but haven't found one that can both add images and edit the text on the existing PDF. Does anyone know of one that I can include in the HTML of my website. Thanks! -
how to append {%includ%} to html using js?
i wanna include post.html inside of home.html, to do this i use jquery to append {%include "post.html"%} to home.html the thing is it appears in home.html like {%include "post.html"%} without being evaluated into the acutal post.html content and that's the porblem i want to use $('body').append('{%include "post.html"%}') to add the post.html to home.html but in home.html all i get is: <!--home.html--> {%include "post.html"%} wut i expect is: <!--home.html--> <div>actual content of post.html</div> -
Template does not exist after splitting the settings in Django
All was working well before I split the settings (development, production). Now I am having an issue with the template doesn't exist. Here are my settings files: base_settings.py """ import os from pathlib import Path BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../')) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'autoslug', 'accounts', 'stellar', 'stellar_sdk', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'stellarLedger.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': os.path.join(BASE_DIR, 'templates'), 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'stellarLedger.wsgi.application' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'nasir.hussain7661106@gmail.com' EMAIL_HOST_PASSWORD = 'enigma.360' EMAIL_USE_TLS = True LOGOUT_REDIRECT_URL = '/' AUTH_USER_MODEL = "accounts.customUser" # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' # STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) # … -
Como recuperar/obter a url da imagem de perfil do usuario logado com o google, em DJANGO
Como estou fazendo: <img src="{{ user.urlphotoprofile }}" Para obter o nome é muito simples basta {{user.username}}, mas ja a photo não consegui, e não encontrei nada na internet a respeito -
concatenate two fields after "ReadOnlyField(source= " in Django rest framework
I have a Django app using Django rest framework as restful api. I want to concatenate two fields after "ReadOnlyField(source= " in Serializer.py Serializer.py: class MaterialSerializer(serializers.ModelSerializer): book = BookSerializer(many=False) course = CourseSerializer(many=False) school = serializers.ReadOnlyField(source='course.courseInfo.school.code', allow_null=True) courseCode = serializers.ReadOnlyField(source='course.courseInfo.discipline_code'+'course.courseInfo.code') #I want to concatenate discipline_code and code, but seems like using "+" could not work class Meta: model = Material fields = ['id', 'book', 'course', 'school', 'courseCode'] How could I concatenate discipline_code and code after "ReadOnlyField(source= "? -
Python/Django ModelViewSet API with routers Page not found (404)
I'm trying to build a geolocation API with Python and Django. I already have a ModelViewSet API endpoint to display Providers at the URL http://localhost:8000/Providers and the Provider's details at http://localhost:8000/Providers/{id}. I need to add another ModeViewSet to the endpoint /Providers/{id} so that I have an API endpoint /Providers/{id}/Polygons to display all polygons created by the provider with that id. Therefore visiting the URL http://localhost:8000/Providers/{id}/Polygons should display all polygons created by Provider with that id and subsequently the details of that polygon. How can I better create the url routers or the API ModelViewSet. Thanks in advance. The code I have keeps telling me this. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/providers/1/polygons .... ^ ^providers/<int:pk>/polygons/$ [name='polygons-list'] ^ ^providers/<int:pk>/polygons\.(?P<format>[a-z0-9]+)/?$ [name='polygons-list'] ^ ^providers/<int:pk>/polygons/(?P<pk>[^/.]+)/$ [name='polygons-detail'] ^ ^providers/<int:pk>/polygons/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='polygons-detail'] ^ ^$ [name='api-root'] ^ ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] The current path, providers/1/polygons, didn't match any of these. The details of the code. Here's the Urls.py: from .apiviews import ProviderViewSet, ServiceAreaViewSet, CreatePolygon, UserCreate, LoginView from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('providers', ProviderViewSet, base_name='providers') router.register(r'providers/<int:pk>/polygons', ServiceAreaViewSet, base_name='polygons') urlpatterns = [ path("login/", LoginView.as_view(), name="login"), # Login path(r'swagger-docs/', schema_view), path(r'docs/', include_docs_urls(title='Polls API')) ] urlpatterns += router.urls Here's the Serializers.py: from .models import Polygon, ServiceArea, Provider class PolygonSerializer(serializers.ModelSerializer): … -
How can objects be reordered using django-sortedm2m?
A Collection object can contain several Item objects, and an Item object can be contained by several Collection objects. The items should be ordered in each collection. I am using django-sortedm2m: from sortedm2m.fields import SortedManyToManyField class Item(models.Model): pass class Collection(models.Model): items = SortedManyToManyField(to=Item) >>> item_1 = Item.objects.create() >>> item_2 = Item.objects.create() >>> collection = Collection.objects.create() >>> collection.items.set([item_2, item_1]) >>> collection.items.all() <QuerySet [<Item 2>, <Item 1>]> As expected, the order of items as they have been added is preserved. However, I want to reorder these elements, in the spirit of a "classic" model with ForeignKeyField and order_with_respect_to: collection.set_item_order([1, 2]). What is the best or simplest way to do that? -
Django : generate a file then save it in a FileField
I have a model Contract. When users create a new Contract, they only have to provide the name. Then, my code will generate a file, and save it in contract_file which is a FileField. For this, I have a static method for generating the file, then I overwrite the save method of django's Model. class Contract(models.Model): name = models.CharField(max_length=150, null=True) contract = models.FileField(upload_to = 'contrats/', blank=True, null=True) def save(self, *args, **kwargs): filename = self.generate_contract() f = open(filename, "r") self.contract.save(filename, f) return super(Refund, self).save(*args, **kwargs) @staticmethod def generate_contract(): filename = settings.MEDIA_ROOT + 'test.txt' f = open(filename, "w") f.write("content") f.close() return filename Unfortunately, this results in an Exception Value: maximum recursion depth exceeded while calling a Python object I suppose that when I call the FileField save method, it might somehow also call the Contract' save method. But I could not solve this problem. Does anyone have a method for performing this file generation then saving it ? -
Django values method - related objects in list [closed]
Hi help with values () method of queryset. When displaying related fields (Foreign key), the data is repeated, can this data be grouped? class Product(models.Model): category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True, db_index=True) class ProductImage(models.Model): product = models.ForeignKey(Product, related_name='product_image', on_delete=models.CASCADE) image = models.ImageField(upload_to='img/models/') is_main = models.BooleanField() Example here This is how it is displayed [ {'pk': 1, 'title': 'Product 1', 'product_image__image': 'img/models/mod_wpYzlnm.png'}, {'pk': 2, 'title': 'Product 2', 'product_image__image': 'img/models/mod2_wEr0D2q.png'}, {'pk': 2, 'title': 'Product 2', 'product_image__image': 'img/models/mod_pPQqmjB_we175uR.png'}, {'pk': 10, 'title': 'Product 3', 'product_image__image': 'img/models/mod_3mTxkb9_z4lKV3l.png'}, {'pk': 10, 'title': 'Product 3', 'product_image__image': 'img/models/heart.png'} ] This is how it should be [ {'pk': 1, 'title': 'Product 1, 'product_image__image': 'img/models/mod_wpYzlnm.png'}, {'pk': 2, 'title': 'Product 2', 'product_image': [ {'image':'img/models/mod2_wEr0D2q.png'}, {'image':'img/models/mod_pPQqmjB_we175uR.png'} ]}, {'pk': 10, 'title': 'Product 3', 'product_image': [ {'image':'img/models/mod_3mTxkb9_z4lKV3l.png'}, {'image':'img/models/heart.png'} ]}, ] -
TweepError at / Unable to access file: No such file or directory when I use can
Hi I started a project which I use Django + tweepy When I wanna tweet with media I save my media in cdn my photo upload successfully on my cdn but tweepy say / Unable to access file: No such file or directory my code : tweet_photo = form.cleaned_data.get('tweet_photo') photo = cloudinary.uploader.upload(tweet_photo, public_id=clean_text) media = photo['url'] api.update_with_media(media, clean_text) Thanks for your helping -
What is the best practice for implementing hierarchical fields in models?
I have below model: class Flower(models.Model): name = models.CharField(max_length=30) country = # I don't know province = # I don't know What is the best practice for implementing hierarchical country and province fields in models? I want that the user can select some countries and provinces from the list, and later he can add or remove them. also when the user select for example Germany from the country field, only provinces related to Germany will show in the province select box field. The user is able to select some countries and provinces -
Django async testing: Cannot operate on a closed database
I need to test some async functions in django and I need to add som decorators in order to enable my async tests to access to the DB. But, it still shows Error Traceback (most recent call last): File "/Users/apple/.local/share/virtualenvs/backend-KucV-wUh/lib/python3.9/site-packages/django/db/backends/base/base.py", line 237, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "/Users/apple/.local/share/virtualenvs/backend-KucV-wUh/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 274, in create_cursor return self.connection.cursor(factory=SQLiteCursorWrapper) sqlite3.ProgrammingError: Cannot operate on a closed database. @database_sync_to_async def create_user(): user = User.objects.create( username='username', ) user.set_password('password') user.save() @pytest.mark.asyncio @pytest.mark.django_db(transaction=True) class WebsocketTests(TestCase): async def test_not_authenticated(self): await create_user() ..... other async functions -
How can i get only text from CKEditors RichTextField in Python?
I have CKEditor and i need the pure text from it in serverside. I tried re.sub to strip tags but it fails when there are tables or images or links how can i avoid them. Thanks in advance. -
Docker auto reload not working on remote server
I've setup a Django project that runs in Docker. I want to have my dev environment on a remote server and have it auto reload as I change my files locally. I've set up remote deployment in Pycharm and it works fine. All local changes are reflected on my remote server, I can also see that files get changed inside the Docker container as I've setup a volume in my docker-compose file. However auto reloading is not working, and I cannot figure out why. -
Connect javascript function with User to add User details (in django)
I am trying to make a website where I have a pomodoro timer.Everything works fine, I have also added login, logout and registration functionalities but now I need to manipulate User data: I would like to make a small calendar, and clicking on a day the User would see the total amount of time he used the timer (on that day).I have no idea how to connect my javascript function with the User, and the django model documentation doesn’t help.Could someone help me showing some code examples or giving some useful links to use.Thank you ;) -
Why do I keep getting 403 Error using Nginx?
I am new to nginx so I am not sure I am understanding it right. What I am trying to is the following redirect: subdomain.domain.com -> subdomain.domain.com/something My config looks like this: server { listen 80; root /MyUser/django-app/example; server_name ~^(?<subdomain>.+).domain.com$; location ~ ^/$ { return 301 http://subdomain.domain.com/something$request_uri; } } Now when I go to subdomain.domain.com I am correctly redirected to subdomain.domain.com/something but I keep getting the 403 Error. When the redirection happens Gunicorn should check the urls.py from my django project and provide the correct view. I think I am missing something but I cannot figure out how to solve this. I can provide additional information if needed. -
Best way to deploy a django project to Azure Ubuntu VM
I have a django project and bitbucket as Git. I would like to deploy the django project to an Azure Vm (Ubunut 20.04). I was wondering can I use bitbucket pipelines to deploy to the VM. Or shall I conternize the Django application to store it on a registry and run the image on the VM. -
Cross queries in django
I have two models as below class Watched(Stamping): user = models.ForeignKey("User", null=True, blank=True, on_delete=models.CASCADE, default=None) count = models.PositiveIntegerField() class Link(Stamping): ... user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) url = models.CharField(max_length=256, default=None) watched = models.ForeignKey(Watched, null=True, blank=True, on_delete=models.CASCADE, default=None) ... A user can create a Link object and when some conditions are met, the object will be added to Watched. The Watched model contains objects created by different users. Now I want to filter the Watched class and grab only the objects created by the requesting user in the Link model but I don't know how I can achieve that. Any help will be appreciated. -
Getting an empty list when using model.objects.filter
I have my API in Django REST Framework: Here is my models.py: class myModel(models.Model): user_email = models.CharField(max_length= 200, null= False) Here is my views.py: class GetItemsByEmail(generics.ListAPIView): def get_queryset(self): email_items = self.request.query_params.get("user_email") if(email_items is not None): itemsReturned = myModel.objects.all().filter(user_email = email_items) return Response(data= itemsReturned) Here is my urls.py: url_patterns = [ path('users/account=<str:id>/items', GetItemsByEmail.as_view()), ] My Question: I am getting an empty list, getting nothing from making an API call to the above endpoint, although I know that there are items with that filter query. I want to get all the items in the database associated with a particular email?