Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I run an async function from a django view to run in the background while I process requests in the main loop?
As I said in the title, I want a task to run in the background processing a large database query while I handle requests from my frontend. Can I even do that with async/asyncio? I was told it was possible... For the purpose of context, I would like to do something like the following. Note also that I don't really need the function to tell me when it's done (though I'd sure like to know if it's possible) since I just check if the .json file was finally written. def post_data_view(request): if request.method == 'POST': ... do_long_query_in_the_background(some_data) return HttpResponse('Received. Ask me in a while if I finished.') def is_it_done_view(request): if request.method == 'GET': data = find_json() if data: return JsonResponse(data) else: return HttpResponse('Not yet dude...') async def do_long_query_in_the_background(data): # do some long processing... # dump the result to a result.json return I was told this was possible with async but I really find it hard to understand. For context, I tried to simplify this a lot, and even then I found I didn't quite understand what was happening: async def f(): while True: print(0) await asyncio.sleep(2) asyncio.create_task(f()) even this code I tried fails sys:1: RuntimeWarning: coroutine 'f' was never awaited, … -
python socketio - open packet not returned by the server
I am trying to connect to a socket server (node.js) say http://localhost:4300. On the server side it has been successfully connected, on my server's log client connected {client_id} but on my client side (python-socketio client) it returns exceptions OPEN Packet not returned by the server Could anyone please help me explain why I got this exceptions? I have been doing what the docs said. -
" Django " category in div id
Hi I have to use Python and Django for our application. I get categories slugs for div id but not working What do you think? I put the required code at the bottom. view.py def my_grouper(n, iterable): args = [iter(iterable)] * n return ([e for e in t if e is not None] for t in itertools.zip_longest(*args)) def home_page(request): sliders = Sliders.objects.get_active_slider().first() projects = Projects.objects.get_active_projects() projects_category = ProjectsCategory.objects.get_active_projects_category() grouped_projects = list(my_grouper(4, projects)) context = { 'slider': sliders, 'projects': grouped_projects, 'projects_category': projects_category } return render(request, 'tarahan/home-page.html', context) list category template {% for category in projects_category %} <li class="p-tab-btn" data-tab="#{{ category.slug }}">{{ category.title }}</li> {% endfor %} for loop for get item {% for project_list in projects %} <div class="p-tab" id="{% for project in project_list %}{{ project.categories.first.slug }}{% endfor %}"> <div class="project-carousel owl-theme owl-carousel"> <!--Gallery Item--> {% for project in project_list %} <div class="gallery-item"> <div class="inner-box"> <figure class="image-box"><img src="{{ project.image.url }}" alt="{{ project.categories.first.slug }}"> </figure> <!--Overlay Box--> <div class="overlay-box"> <div class="overlay-inner"> <div class="content"> <a href="{{ project.image.url }}" class="lightbox-image image-link" data-fancybox-group="example-gallery" title=""><span class="icon fa fa-expand"></span></a> <a href="{{ project.get_url }}" class="image-link"><span class="icon fa fa-link"></span></a> </div> </div> </div> </div> </div> {% endfor %} </div> </div> {% endfor %} thanks -
i am getting a Python Error: list index out of range
i am trying to loop through a 2d array to append the first item to a different list. When i try to loop through and append it gives an error. error: list index out of range here is the code #there is a loop that creates a 2d array that goes like this [[object, int], [object, int], [object, int]] sorted_list = sorted(temp_list, key=lambda x: x[1], reverse=True) #the above code sorts this list by the second value in the inner arrays of the 2d array for x in sorted_list: y = x[0] post_list.append(y) #the above code loops through the sorted list and should append the first value of each inner list #to the list post_list note that if i change the loop to: for x in sorted_list: print(x[0]) then it doesn't give an error, it just outputs this object object object why am i getting the out of range error? -
REST API versioning pattern guide
I am writing huge Rest API, to make it easily discoverable, i am making the pattern like this way. http://127.0.0.1:8000/membership/api/v1/make-a-payment But i notice poeple used to make the pattern like this way: http://127.0.0.1:8000/ap/v1/blabla Can you anyone tell me what is the best practice? is it ok writing pattern like this way? http://127.0.0.1:8000/membership/api/v1/make-a-payment ? I just trying to make it easily discoverable by swegger docs. What is your opinion? -
DRF Update price of a product via Viewset Interface
My model for this is straight simple, but I fail to create a "handsome" interface on the ViewSet Template: class Product(models.Model): id = models.PositiveIntegerField(unique = True) price = models.DecimalField(Price, default = 0) name = models.CharField("name", max_length = 128) I created a serializer: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["id", "name", "price"] and I added a ViewSet: class LoadPageViewSet(viewsets.ViewSet): serializer_class = ProductSerializer http_methods = ["get", "put"] def list(self, request): query = Product.objects.all() results = ProductSerializer(data = query, many = True) results.is_valid() return Response(data = results.data, status = status.HTTP_200_OK) def put(self, request): serializer = LoadPageSerializer(data = request.data) if serializer.is_valid(): P = Product.objects.get(id = request.data["id"]) P.price = request.data["price"] P.save() return Response(serializer.data, status = status.HTTP_200_OK) return return Response(serializer.data, status = status.HTTP_400_BAD_REQUEST) If I execute this, when I choose a new price I run into the unique constraint of the id field: product with this id already exists.. -
Setting Djando field default value based on another field
I am creating a Django model where: expirationTimeStamp field's default value is based on creationTimeStamp isLive boolean field value is based on expirationTimeStamp I have written the following functions expirationTimeCalculation and postLiveStatus and assigned them as default values to the fields but I am getting error. I have also tried to assign to respective fields through property(function) yet I am still getting error. One of the functionality that I need to implement is that user can send custom expirationTimeStamp as well that would override default value, therefore, I believe property(function) assignment is not ideal for expirationTimeStamp field. Is there any other way that I can go about to set the expirationTimeStamp field value based on creationTimeStamp field? Any feedback is appreciated! class Posts(models.Model): def expirationTimeCalculation(self): EXPIRATION_DURATION = 86400 #time in seconds expirationTime = self.creationTimestamp + timedelta(seconds = EXPIRATION_DURATION) return expirationTime def postLiveStatus(self): return (self.expirationTimestamp > timezone.now) message = models.TextField() creationTimestamp = models.DateTimeField(default=timezone.now) expirationTimestamp = models.DateTimeField(default=expirationTimeCalculation) isLive = models.BooleanField(default=postLiveStatus) -
testdriven.io Tutorial broke: Dockerizing Django with Postgres, Gunicorn, and Nginx
https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/ Learning Fullstack. Have done a little Docker, a lot of python, but no NGINX stuff. 60% through this tutorial I am failing at the end of NGINX section. The Nginx container builds and starts with the other two but stops immediately. And I of'course get a 404 on the localhost and port specified. Just to eliminate any screwy localhost issues on my Mac, I ran an Nginx container directly from the Docker command.... docker run -p 80:80 nginx It ran fine. No so with my tutorial project. The project is literally bog standard from the tut, but here are some specifics. docker-compose.prod.yml: version: '3.7' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn hello_django.wsgi:application --bind 0.0.0.0:8000 expose: - 8000 env_file: - ./.env.prod depends_on: - db nginx: build: ./nginx ports: - 1337:80 depends_on: - web db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db volumes: postgres_data: nginx/Dockerfile - FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d nginx/nginx.conf upstream hello_django { server web:8000; } server { listen 80; location / { proxy_pass http://hello_django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } -
DRF ViewSet: Change appearance of field
I have a model like this: ## model: class Product(models.Model): id = models.PositiveIntegerField(unique = True) price = models.ForeignKey(Price, on_delete = models.CASCADE, null = True, blank = True) ## serializer: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["id", "price",] which shows up in the template of the API like this: I get, this is because of the nature of the model field type. Two questions here: Can I get rid of the little arrows somehow and make a normal field? Could I somehow return a list of all Product ids like for the price? Something like ids = Product.objects.values_list("id", flat = True) or so? -
Django Blog, Only Update Publish Date if not Already Published
So I've built a very basic blog in Django. I have been working on adding a new feature allowing me to save a new post as a draft to publish later, or to unpublish an already published post. I'm fairly new to Django/Python, so perhaps I'm making a novice mistake here. To achieve this, I've added two fields to my Post model. A BooleanField named published and a DateTimeField named publish_date. I only ever want publish_date to update when publish is set to True & was previously False. The approach I've taken is to override the save() method of my Post model. Within the method, I am either setting publish_date to None (if published is unchecked on the form) or I am setting publish_date to timezone.now() (if published is checked on the form). This approach is okay, although publish_date will be updated everytime the post is updated, even if it has not been unpublished/republished. This cannot happen. I'm still learning about the interactions between views, models, and forms, so I really appreciate any guidance. Please take a look at all relevant code and let me know of a better approach to solving this. Thank you for your help! models.py class … -
'str' object has no attribute 'match_key' when sorting dictionary
Full error: 'str' object has no attribute 'match_key' I am trying to sort a dictionary by the values of one of the keys in the objects but I am running into errors whem doing so. What is the best way to do this kind of sort? Code: x = { 'id': f'{item.id}', 'post': item, 'match_key': match_percentage } temp_dict.update(x) sorted_dict = sorted(temp_dict, key=operator.attrgetter('match_key')) -
How do you add a text placeholder without changing the model to a form?
So this this post shows how you would use a placeholder for a textfield if you wanted to change the model to a form. But if I want to keep the model as a model so that I don't need to write a form, how can I add a placeholder in the textbox that disappears when the user clicks it? Here's my current model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) firstName = models.CharField(max_length = 25, null=False, blank=False, default="Enter your first name") I want to switch default to blank and add "Enter your first name" as a placeholder so the user doesn't need to delete the text when he or she wants to fill in the information. However, I don't want to turn it into a form. -
How can I automatically add a Django command to each log?
Right now I have a Django command named log_test. class Command(BaseCommand): help = '' def handle(self, *args, **options): logging.info("This is a log test") My log formatter looks like this 'formatters': { 'standard': { 'format': '%(message)s [%(request_id)s]{%(user_id)s}' }, }, So when I run python manage.py log_test the above function will log This is a log test [abc]{12} I would like to update this so that the log reads This is a log test [abc]{12} script=log_test Is there an easy way to do this using Django? In summary want each log that originated from a Django command to also log the name of the Django command. -
Django forgot password email giving invalid token on Mac and iPad
I have a Django application running on a Windows server. I have used the "Forgot Password" option numerous times without a problem. A user complained that on a Mac using Firefox, she got an invalid token when she clicked on the link in the password reset email. I could not duplicate it on my Windows PC using Chrome or Firefox. However, I tried it on an iPad, and I got the same behavior as she (I don't have a Mac to try). I tried it several times with the same result. The link in the email that I send looks like this: https://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} I opened the same email from my Windows PC, and that link in my password reset email worked without a hitch (it generates a reset page with the address "https://myserver.com/reset/MTE/set-password/"). My ipad gets to the same page, but with an invalid token. Does anyone know what might be going on here and how to fix it? Thanks-- Al -
Django Static Image Not Serving
I have a simple django app I am trying to build and I am trying to display an image on the front page. When i load the front page the image is not there. But when i go directly to the image url it shows just fine. I have been following the django documentation and I can not seem to solve this issue. My site structure is like this Main Dir -app -website -static --images Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ('/path/to/static/root/directory/',) DIRNAME = os.path.dirname(__file__) STATIC_ROOT = os.path.join(DIRNAME, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] base.html {% load static %} <div class="parallax"><img src="{% static 'images/frontbannar.jpg' %}" alt="Unsplashed background img 1"></div> I have also run this command and it did not work. python manage.py collectstatic -
Javascript undifined error while using dataset with django templates
I get undefined error while using JS dataset to try to get data from a django template i cant fix it, can anyone provide a solution. The index.html template <div id="currentUser1" data-currentUser="1"></div> For the JS code document.addEventListener('DOMContentLoaded', function(){ let currentuser2 = document.querySelector('#currentUser1').dataset.currentUser; console.log(currentuser2) }); The out on the browser undefined network.js:4:13 Thats the error I get, and as for the console everything is okay with no errors. -
Is it possible to reset a password without a token? django + react
Could I reset a password for a user without a token , which (ithink) would require sending a link via a email to a users email address (I'm not sure if django or react have that functionality) So could I rewrite their password data with a axios post request if I had most details of their account like username,email,user_id. -
error while trying to run Unittest with PostgreSQL db inside docker container
I have this Django app which runs inside Docker. I am trying to run some test on a script. I run this command below but receive the following error: any idea? iam new to docker and postgresql and django as well.. docker-compose run web sh -c "python manage.py test test test.unit.enrollments.test_views.MyAPIViewTestCase.test_id" =========================================================== ERROR: test.unit.transactions.test_views (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: test.unit.transactions.test_views Traceback (most recent call last): File "/usr/local/lib/python3.5/unittest/loader.py", line 428, in _find_test_path module = self._get_module_from_name(name) File "/usr/local/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name __import__(name) File "/opt/app/test/unit/transactions/test_views.py", line 15, in <module> from test.unit.transactions.view_testing_utils import ViewTestingUtils File "/opt/app/test/unit/transactions/view_testing_utils.py", line 9, in <module> from test.unit.groups.view_testing_utils import ViewTestingUtils as SharedViewTestingUtils File "/opt/app/test/unit/groups/view_testing_utils.py", line 27, in <module> class ViewTestingUtils: File "/opt/app/test/unit/groups/view_testing_utils.py", line 169, in ViewTestingUtils status=LargeGroupGroupStatus.IN_PROGRESS.value, File "/usr/local/lib/python3.5/enum.py", line 274, in __getattr__ raise AttributeError(name) from None AttributeError: IN_PROGRESS ---------------------------------------------------------------------- Ran 138 tests in -70489110.777s FAILED (errors=168, skipped=8) Destroying test database for alias 'celery'... ERROR: 1 -
AWS Elastic Beanstalk Deployment Error: 502 Bad Gateway - Django Application
I am having problems deploying my 1st python django app to AWS Elastic Beanstalk. The app appears to upload correctly but when I try to use it I get 502 Bad Gateway. The logs show the following: *2021/03/25 20:14:53 [error] 5144#0: 357 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.8.43, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "crap-env.eba-2nhwp4ty.us-west-2.elasticbeanstalk.com" Would appreciate any help. -
I don't understand how sorl-thumbnail uses db and also a cache
I'm trying to get my head around how sorl-thumbnail works but getting a bit confused. I know it get's a key depending on the image and its settings then saves/returns the value when it's needed. To me this seems like it would all be done with the cache. I just don't get why it's saving the key/value in a database too. Can you explain why you need a cache engine and also a database? It doesn't make sense to me why it would need to use both. -
How to render different templates per user status
I want to render a different template per user is_teacher status. here is my model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_teacher = models.BooleanField(default=False) here is my view.py def home(request): if User.profile.is_teacher==True: return render(request, 'home/home.html') else: return render(request, 'home/tutor_home.html') I am having issues with the second line, I want a situation where if is_teacher is true in user profile then it renders a template and if false it renders another template -
Any developers looking to join a Bio- Tech Start up on contractor rate?
I am looking for London based Back End & Front End Developers who are readily available and have previous experience working in a Start-Up environment is key. Key technologies Python, Django, Rest Framework, React, TypeScript, Ionic, Node.js, PostgreSQL, NoSQL, TDD, Gitflow, CI/CD, AWS If you are interested please do make contact with a copy of your updated CV. NO AGENCIES PLEASE. -
How to convert PIL image to InMemoryUploadedFile
How can i store PIL image into database,whenever try to convert PIL image into InMemoryUploadedFile that time we get an error like 'JpegImageFile' object has no attribute 'read'.Thank u //views.py file FIRST_NAME = request.POST["FIRST_NAME"] LAST_NAME = request.POST["LAST_NAME"] BLOOD = request.POST["BLOOD"] CONTACT = request.POST["CONTACT"] ADDRESS = request.POST["ADDRESS"] image = Image.new('RGB', (640, 480), (255, 255, 255)) # produces white color 255 255 255 image.save('temp.jpeg') image = Image.open('temp.jpeg') print(image.load()) pic_file = InMemoryUploadedFile(file=image, field_name=None, name=image.filename, content_type=image.format,size=image.size, charset=None) ins = person_data(FIRST_NAME=FIRST_NAME, LAST_NAME=LAST_NAME, BLOOD_CUST=BLOOD,CONTACT_CUST=CONTACT, ADDRESS_CUST=ADDRESS, IMAGE_CUST=file, ID_CUST=pic_file) ins.save() //model.py class person_data(models.Model): FIRST_NAME = models.CharField(max_length=50, default='') LAST_NAME = models.CharField(max_length=30, default='') BLOOD_CUST = models.CharField(max_length=30, default='') CONTACT_CUST = models.IntegerField(default=0) ADDRESS_CUST = models.CharField(max_length=30, default='') IMAGE_CUST = models.ImageField(upload_to='images/', default='',null=True, verbose_name="") //Console error 'JpegImageFile' object has no attribute 'read' Internal Server Error: / -
django-graphql-jwt with django-phone-field Object of type PhoneNumber is not JSON serializable
I'm currently using the django-phone-field library in a project where I use graphene-django as well. Here's my custom User model, where I'm using the PhoneField. class User(AbstractBaseUser, PermissionsMixin): """ Custom User model to add the required phone number """ first_name = models.CharField( max_length=100 ) last_name = models.CharField( max_length=100 ) email = models.EmailField( verbose_name='Email address', max_length=255, unique=True, # Because it's unique, blank is not an option because there could be 2 with the same value ('') blank=False, null=True ) phone = CustomPhoneField( # Please note this formatting only works for US phone numbers right now # https://github.com/VeryApt/django-phone-field#usage # If international numbers are needed at some point, take a look at: # https://github.com/stefanfoulis/django-phonenumber-field E164_only=True, unique=True ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'phone' REQUIRED_FIELDS = ['first_name', 'last_name',] I'm using django-graphql-jwt to handle authentication. Here's my tokenAuth query: mutation TokenAuth ($phone: String!, $password: String!) { tokenAuth(phone: $phone, password: $password) { token payload refreshExpiresIn } } The server is retrieving me an error when trying to execute that query: { "errors": [ { "message": "Object of type PhoneNumber is not JSON serializable", "locations": [ { "line": 2, "column": 5 } ], "path": [ "tokenAuth" ] } ], "data": { … -
How can I make Django create migration files for tables that aren't Django managed?
Background I've got a Django app that I want to test. The Django app relies on database tables that were created by a different, non-Django app, but in the same database. Every time I try to run a test I get the following error: django.db.utils.ProgrammingError: relation "mytable" does not exist I'm thinking that this error is caused by the fact that the table was created manually and there are no migrations. Question Is there a way I can tell Django to build migration files based off of a database table that already exists?