Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Rest Framework foreignkey field to be a selectField in my react app
I`m trying to create my serializers for my React app but I met some problems. I will give you an exemple class City(models.Model): city_name = models.CharField(max_length=100) class Profile(models.Model): city = models.ForeignKey(City, on_delete=models.DO_NOTHING) .......more fields....... Right now I thinking how to do the serializer. In GET request things are simple but on POST or PUT request I need all data from City model in my React app to select an option. I thing to do two serializers and in React to have two axios but I`m trying to find another solution. Can anyone faced with this problem to help me? Sorry for my english -
How can run webdriver (selenium) using Celery in Django?
I need to run webdriver periodically (e.g. every minute). I chose crontab. But when I start celery -A proj beat -l info, I get only Sending due task task-number-one (app.tasks.run1) CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'app.tasks.run1', 'schedule': crontab(minute='*/1') }, tasks.py @app.task def run1(): print(333) driver = init_driver() parse2(driver) driver.quit() return HttpResponse('ok') -
seek() takes 2 positional arguments but 3 were given
I am uploading an image to memory then I want to save it to an imageField(). I use django-storages that uploads files from image/fileField() to AWS S3. I download the image to the memory: r = requests.get(url, headers=header) image = Image.open(BytesIO(r.content)) image_in_memory = InMemoryUploadedFile(image, None, "foo.png", 'image/png', image.size, None) image_in_memory_file = image_in_memory.file Some verifications: print(type(image_in_memory)) --- <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> When I save this: my_object.cover.save(name="foo.png", content=image_in_memory) Django generates this error: web_1 | link.cover.save(name="foo.png", content=image_in_memory) web_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/files.py", line 87, in save web_1 | self.name = self.storage.save(name, content, max_length=self.field.max_length) web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/files/storage.py", line 52, in save web_1 | return self._save(name, content) web_1 | File "/usr/local/lib/python3.7/site-packages/storages/backends/s3boto3.py", line 491, in _save web_1 | self._save_content(obj, content, parameters=parameters) web_1 | File "/usr/local/lib/python3.7/site-packages/storages/backends/s3boto3.py", line 505, in _save_content web_1 | content.seek(0, os.SEEK_SET) web_1 | TypeError: seek() takes 2 positional arguments but 3 were given Do you see the problem? -
Fetch parent child relation with level from the same table [ django / python ]
Hi I'm new with django and python. # function for fecthing the child def get_childern(request, username): Q = list(Profile.objects.filter(sponsor_id__exact=username)) populate(request, Q, username) # Iterate the Queryset def populate(request, quesryset, username): if quesryset: messages.success(request, username+' has '+str(len(quesryset))+' child') messages.info(request, quesryset) for user in quesryset: get_childern(request, user.user_id) else: messages.warning(request, 'User '+username+' has no child') return False # calling all children get_childern(request, username) and I want to add the level, how to break it down further. Please help me, invest lots of time and mind. Thanks to all :) -
AttributeError: 'tuple' object has no attribute 'stripe_customer_id'
I am receiving the error below when attempting to submit a purchase using stripe api within django app. line 115, in post if userprofile.stripe_customer_id != '' and userprofile.stripe_customer_id is not None: AttributeError: 'tuple' object has no attribute 'stripe_customer_id' [09/Oct/2019 19:18:26] "POST /api/checkout/ HTTP/1.1" 500 16291 Everything was working until i made alterations based on 22:33. This is line 115: if userprofile.stripe_customer_id != '' and userprofile.stripe_customer_id is not None: customer = stripe.Customer.retrieve( userprofile.stripe_customer_id) customer.sources.create(source=token) Here is the full code where line 115 exists: from django_countries import countries from django.db.models import Q from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.http import Http404 from django.shortcuts import render, get_object_or_404 from django.utils import timezone from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST from core.models import Item, OrderItem, Order, Address, Payment, Coupon, Refund, UserProfile, Variation, ItemVariation from .serializers import AddressSerializer, ItemSerializer, OrderSerializer, ItemDetailSerializer import stripe stripe.api_key = settings.STRIPE_SECRET_KEY class UserIDView(APIView): def get(self, request, *args, **kwargs): return Response({'userID': request.user.id}, status=HTTP_200_OK) class ItemListView(ListAPIView): permission_classes = (AllowAny,) serializer_class = ItemSerializer queryset = Item.objects.all() class ItemDetailView(RetrieveAPIView): permission_classes = (AllowAny,) serializer_class = ItemDetailSerializer queryset = Item.objects.all() class AddToCartView(APIView): def post(self, request, *args, **kwargs): … -
FTP file upload immediately goes to "Failed transfers" with reason "Transferring"
I got a small 2,3kb Activate file for Django, which I need to manually transfer to my server with some fixed code. When I try to upload the file, it goes as the title says immediately to the "Failed transfers" tab. I have deactivated all virtual envs which could be using the file, and testing shows that I can't upload any files at all suddenly. Any ideas what this might be? First time I run into something like this without any errors. -
How to send editext data to firestore in timestamp format?
I'm new to android development and i face a problem in send data of editext to firestore database in format of timestamp . -
In Django, how do I enable users to join a group if the user knows the group password?
In Django I'd like to allow logged-in users to join a group if they enter the right PIN/password. Users should not be able to see what groups exist, instead the user enters a PIN and if that PIN matches the PIN for an existing group, then the user becomes a member of that group. Most of the answers I find are related to user authentication. class Group(models.Model): name = models.CharField(max_length=16) pin = models.IntegerField(unique=True) members = models.ManyToManyField(User, related_name='members', blank=True) Using the model above, I'd like any user who enters a pin that matches an existing pin to become a member of the corresponding group. I'm also open to other ways to structure this, if you can offer a recommendation. I'd like to avoid inviting users to join the group via email or other ways. -
Learning more advanced object oriented patterns in python
Hopefully this question will be useful to others that are looking into learning better practices in python and will serve as a future resource. What are some good resources to learn more advanced python object oriented programming. For example, understanding patterns such as used in the django source code: class FieldFile(File): def __init__(self, instance, field, name): super().__init__(None, name) self.instance = instance self.field = field self.storage = field.storage self._committed = True def __eq__(self, other): # Older code may be expecting FileField values to be simple strings. # By overriding the == operator, it can remain backwards compatibility. if hasattr(other, 'name'): return self.name == other.name return self.name == other def __hash__(self): return hash(self.name) # The standard File contains most of the necessary properties, but # FieldFiles can be instantiated without a name, so that needs to # be checked for here. def _require_file(self): if not self: raise ValueError("The '%s' attribute has no file associated with it." % self.field.name) -
Manager isn't available; 'auth.User' has been swapped for 'users.User'
1 I have a problem with my code when I want signup error to appear Manager isn't available; 'auth.User' has been swapped for 'users.User' , I try a solution of other questions the same as Manager isn't available; 'auth.User' has been swapped for 'members.customer' but all of them asking to replace User = User = get_user_model() but I am not use any User in my code or I dont know where I used that.I'm new in django, python, js and etc so if my question is silly to forgive me. AttributeError at /accounts/signup/ Manager isn't available; 'auth.User' has been swapped for 'users.User' Setting.Py: AUTH_USER_MODEL = 'users.User' LOGOUT_REDIRECT_URL = '/' LOGIN_REDIRECT_URL = '/' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'users.backends.EmailBackend', ) **# Application definition** INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'avatar', 'homepage', 'products',`enter code here` #user part 'users', ] user/models.py: from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth import get_user_model # Create your models here. class User(AbstractUser): nickname = models.CharField(max_length = 50, blank = True) class Meta(AbstractUser.Meta): pass accounts/models.py: from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User #from django_countries.fields import CountryField from django.conf import settings User= … -
NameError: name 'Profile' is not defined
i am trying to update a profile in profile page and create a form. i import form and use ModelForm but my model is not accepting profile data. and it is showing name error. i can not find suitable answer for this problem. -
he SECRET_KEY setting must not be empty - Even when SECRET_KEY is set in settings.py
I keep getting this error when i try to import my models.py file into views.py or any of the other python script in my App directory, i have the SECRET_KEY in settings.py, i have my app in the list of installed_APPS, wsgi.py contains os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings') - i replaced my project name manage.py also contains os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings') this is all i saw was wrong with other people's installations in all the other stackoverflow posts. My code works but importing models just breaks it i use this command to import my class from app_name.models import suscribers and subscribers is defined thus class subscribers(models.Model): name = models.CharField('Name', max_length=120) email = models.CharField('Email', max_length=120) access_token = models.TextField() expires_in = models.DateTimeField('token expiry date') i have already executed makemigrations and migrate commands but being a newbie i don't know where else to look. Please save a soul its been 3 days thanks. -
Django: How to reduce validation code for list of uuid4
All query params will take list of alias. Tryig to do it in simple way.But It has repeat loop from app.helper import uuid4_validator oders =self.request.queryparams("orders", "") #list or string , this field no mendatory products =self.request.queryparams("orders", "") #list or string , this field no mendatory custom_filter = {} if orders: temp_list=[] for temp in orders: if uuid4_validator(temp): temp_list.append(temp) custom_filter["Order__alias__in"] = [temp_list] if products: temp_list=[] for temp in products: if uuid4_validator(temp): temp_list.append(temp) custom_filter["Product__alias__in"] = [temp_list] Stock.object.filter(**custom_filter).update(price=400) -
Multiple functions running in the background
There are 2 functions, a and b. It is necessary that both functions work in the background. The first function should work continuously in a circle, and the second will have to run periodically - with an interval of 5 minutes, for example. What is the best way to implement this? Celery? -
Getting validation error 'is_staff': ["'true' value must be either True or False."] while implementing SSO using djangosaml2
I tried to implement SSO for my Django project. when I tried to login form SP ('/sso/login') I got the correct response from my IDP but on SP side 'sso/acs' it throwing a validation error. {'is_superuser': ["'true' value must be either True or False."], 'is_staff': ["'true' value must be either True or False."]} When I removed is_staff and is_superuser from SAML_ATTRIBUTE_MAPPING. SSO is working. Project packages - django 1.11, postgress, djangosaml2idp 0.5.0, for IDP djangosaml2 0.17.2 for SP My setting for SP: SAML_USE_NAME_ID_AS_USERNAME = True SAML_DJANGO_USER_MAIN_ATTRIBUTE = 'email' SAML_DJANGO_USER_MAIN_ATTRIBUTE_LOOKUP = '__iexact' SAML_CREATE_UNKNOWN_USER = False SAML_LOGOUT_REQUEST_PREFERRED_BINDING = saml2.BINDING_HTTP_POST SAML_ATTRIBUTE_MAPPING = { # SAML : DJANGO # Must also be present in attribute-maps! 'email': ('email', ), 'username': ('username', ), 'account_id': ('account_id', ), 'is_staff': ('is_staff', ), 'is_superuser': ('is_superuser', ), } Error Traceback: Traceback (most recent call last): File "/Users/patilliteshc/Virtual_Envs/spEnv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/patilliteshc/Virtual_Envs/spEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/patilliteshc/Virtual_Envs/spEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/patilliteshc/Virtual_Envs/spEnv/lib/python3.6/site-packages/django/views/decorators/http.py", line 40, in inner return func(request, *args, **kwargs) File "/Users/patilliteshc/Virtual_Envs/spEnv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/patilliteshc/Virtual_Envs/spEnv/lib/python3.6/site-packages/djangosaml2/views.py", line 316, in assertion_consumer_service create_unknown_user=create_unknown_user) File "/Users/patilliteshc/Virtual_Envs/spEnv/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 73, in authenticate user = backend.authenticate(request, **credentials) … -
Database queries to 'cache' are not allowed in this test in django 2.2
I'm migrating project to django 2.2 from django 1.11. We have database based cache that runs on different database (not on default). When running tests, we get the following error: AssertionError: Database queries to 'cache' are not allowed in this test. Add 'cache' to users.tests.UserLogTestCase.databases to ensure proper test isolation and silence this failure. Adding the 'cache' database to the databases variable of the TestCase solves the problem (or setting it to '__all__'), the problem is that this has to be done per test. Is there any other (more global) way to solve this? -
Is there any source where I can go to learn how to make a not realtime messaging system with django, maybe using modules
I want to start a messaging system in my website, and I have tried to make a messaging system with Channels but I have a problem with the WS and the WSS for the websocket and I don't really know how to fix it, so I was wondering if there are any other ways to do this. Thanks for any help -
Connecting to EC2 Django Server
1. I have opened port 8001 on inbound traffic on EC2 security group. 2. Ran python manage.py runserver 0.0.0.0:8001 Shows 'Starting development server at http://0.0.0.0:8001/' 3. Tried to access the public EC2 address (ipv4 public 60.x.x.1:8001 or Public DNS (IPv4) http://ec2-x.x.x.compute.amazonaws.com:8001) I also added the public address above to the settings.py I can't seem to get the page loading. What needs to be done here? I get either not accessible or This site can’t be reached. -
All allowed hosts in settings file not working on Django site on Windows machines
The main allowed host - www.mysite.com is working on all browsers/ios/android/etc. However, mysite.com is not working on all browsers. It's a Django site and I've added these two allowed hosts into the settings file. It's only working on Chrome and Safari. How do I fix this for Windows machines? -
Structuring my Axios POST request to send my Django Rest Framework Stripe form data
I am working with default Stripe code to generate a Token that proves the payment form was successfully submitted. I'll post the code below for clarity within this post. I'm able to see the token if I console.log(token), but my server (Django Rest Framework) is giving me a 500 error with django.utils.datastructures.MultiValueDictKeyError: 'stripeToken' . From my limited research, this is saying the request.POST doesn't see a key of stripeToken. Do you think this is an error on how my server is handling this, or could I have written some incorrect Javascript? Here is my VueJS code: mounted: function () { var that = this; var stripe = window.Stripe(process.env.STRIPE_PUBLISHABLE_KEY_TEST); var elements = stripe.elements(); var style = { base: { color: '#32325d', fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: 'antialiased', fontSize: '16px', '::placeholder': { color: '#aab7c4' } }, invalid: { color: '#fa755a', iconColor: '#fa755a' } }; var card = elements.create('card', {style: style}); card.mount('#card-element'); card.addEventListener('change', function (event) { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ''; } }); var form = document.getElementById('payment-form'); form.addEventListener('submit', function (event) { event.preventDefault(); stripe.createToken(card).then(function (result) { if (result.error) { var errorElement = document.getElementById('card-errors'); errorElement.textContent = result.error.message; } else { stripeTokenHandler(result.token); } }); … -
Django Convert F type to float on query
I have 2 model in django a zone and a shop, models are like this: from django.contrib.gis.db import models from django.contrib.gis.geos import Point from django.contrib.gis.measure import D from location_field.models.spatial import LocationField class Zone(models.Model): name = models.CharField(max_length=200) location_point = LocationField(based_fields=['city'], zoom=7, default=Point(51.67, 32.65)) radius = models.IntegerField(default=1000) # radius in meters class Shop(models.Model): name = models.CharField(max_length=200) location_point = LocationField(based_fields=['city'], zoom=7, default=Point(51.67, 32.65), null=True, blank=True) zone = models.ForeignKey(Zone, on_delete=models.CASCADE, null=True) LocationField is a PointField with better map in django admin. I want on every shop saving select zone automatically base on shop location , zone location and radius. If there is no zone with radius to support shop it will be None. I tried this query: zone_list = Zone.objects.filter(location_point__distance_lte=(shop.location_point, D(m=models.F('radius')))) But I get this error: TypeError: float() argument must be a string or a number, not 'F' How can I fix this? -
POSTMAN: Post method using raw body returns 500
I tried to POST a query in json in postman's raw body like below: and I got 500 internal error server and HTML results like below Otherwise, I'm able to POST using form-data and from a script ran from the terminal using the same json format. I use Django 1.5.12 to serve the API and python 2.7. Can anyone help? -
How to run Celery schedule only a number of times and quite until the task is called again?
I am using django + celery task scheduler to run a task scheduled for once every month. But I just want this task to run for a few number of months only, e.g 3 months or 6 months or 9 months.. How do I get to stop the worker from executing further task and then restarting whenever the task is called again? -
How to add permissions to edit own in django admin based on value in model?
I have a question about Django-Admin. Every item in my Django admin has got the "EngagementManager" field, which contains the name of the person. When you log in Django, your username is the same as the field, which I mentioned previously. I need to implement the feature that login user could change/edit only items when the field "EngagementManager" will match the login user. Can someone please provide me the piece of code and some little guide where to put it, please? -
Python-kenel error:PermissionError: [Errno 13] Permission denied:
I set a enviroment of tensorflow. I wanna to check whether it works well.So I open the Jupyter Notebook When I open Jupyter Notebook and establish a new file, it show kenel error. Traceback (most recent call last): File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\web.py", line 1699, in _execute result = await result File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\gen.py", line 742, in run yielded = self.gen.throw(*exc_info) # type: ignore File "D:\Anaconda3\envs\tensor36\lib\site-packages\notebook\services\sessions\handlers.py", line 72, in post type=mtype)) File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\gen.py", line 735, in run value = future.result() File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\gen.py", line 742, in run yielded = self.gen.throw(*exc_info) # type: ignore File "D:\Anaconda3\envs\tensor36\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 88, in create_session kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name) File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\gen.py", line 735, in run value = future.result() File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\gen.py", line 742, in run yielded = self.gen.throw(*exc_info) # type: ignore File "D:\Anaconda3\envs\tensor36\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 101, in start_kernel_for_session self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_name) File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\gen.py", line 735, in run value = future.result() File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\gen.py", line 209, in wrapper yielded = next(result) File "D:\Anaconda3\envs\tensor36\lib\site-packages\notebook\services\kernels\kernelmanager.py", line 168, in start_kernel super(MappingKernelManager, self).start_kernel(**kwargs) File "D:\Anaconda3\envs\tensor36\lib\site-packages\jupyter_client\multikernelmanager.py", line 110, in start_kernel km.start_kernel(**kwargs) File "D:\Anaconda3\envs\tensor36\lib\site-packages\jupyter_client\manager.py", line 240, in start_kernel self.write_connection_file() File "D:\Anaconda3\envs\tensor36\lib\site-packages\jupyter_client\connect.py", line 547, in write_connection_file kernel_name=self.kernel_name File "D:\Anaconda3\envs\tensor36\lib\site-packages\jupyter_client\connect.py", line 212, in write_connection_file with secure_write(fname) as f: File "D:\Anaconda3\envs\tensor36\lib\contextlib.py", line 81, in __enter__ return next(self.gen) File "D:\Anaconda3\envs\tensor36\lib\site-packages\jupyter_client\connect.py", line 102, …