Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query number of occurences of a character in CharField
I have a CharField who contains paths, like: zero/one/two/three , or root/usr/et_cetera The number of separators (here /) give us the depth of the 'node' in the path, so on the previous example, three has a depth of 3. In python, I could write 'zero/one/two'.count('/'), but I wonder how to do it in a Django query. What I search is something like following: # Hypothetical code, does not work Model.object.annotate(depth=CountChr('path', V('/'))).filter(depth=2) I can't find a function who does that in the django documentation. -
Cannot Iterate through the array list in Django
I'm iterating through all the records from database but only one the first row is reflecting in the output. The database data which are list of tuples [(('HR749', datetime.datetime(2021, 11, 5, 20, 0, 17), 'Web', 'Referrals ', 'Draft', 'Bus', 'India', 'satish', 10902, 'Openings', datetime.date(2021, 11, 10),('HR855', datetime.datetime(2021, 11, 5, 20, 11, 41), 'Web', 'Referrals ', 'Draft', 'BusS', 'India', 'mah', 83837, ' referral', datetime.date(2021, 11, 10)), ('HR929', datetime.datetime(2021, 11, 5, 20, 22, 58), 'Web', 'Referrals ', 'Draft', 'BusS', 'India', 'ritika', 6124, 'Unable to submit', datetime.date(2021, 11, 10))] Here, what I have tried I know its simple but I don't know why I couldn't able to get all the records from the database views.py: @api_view(['GET', 'POST']) def ClaimReferenceView(request,userid): try: userid = Tblclaimreference.objects.filter(userid=userid) except Tblclaimreference.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': userID = request.data.get(userid) print(userID) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetClaims] @UserId= %s',('10',)) result_set = cursor.fetchall() print(type(result_set)) print(result_set) for row in result_set: Number= row[0] Opened = row[1] Contacttype = row[2] Category1 = row[3] State = row[4] Assignmentgroup = row[5] Country_Location = row[6] Openedfor = row[7] Employeenumber = row[8] Shortdescription = row[9] AllocatedDate = row[10] return Response({"Number":Number,"Opened":Opened, "Contacttype": Contacttype, "Category1":Category1, "State":State, "Assignmentgroup":Assignmentgroup, "Country_Location": Country_Location, "Openedfor":Openedfor, "Employeenumber":Employeenumber, "Shortdescription": Shortdescription, "AllocatedDate":AllocatedDate}, status=status.HTTP_200_OK) -
NOT NULL constraint failed:orders_order.user_id
I am new to django and i am building an ecommerce website. When i try to make a new order in my website i got this error: NOT NULL constraint failed:orders_order.user_id each user can have multiple orders and i want to show the orders in the users profile but i am having problem with placing orders models.py class Order(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) address = models.CharField(max_length=250) postal_code = models.CharField(max_length=11) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return f'Order {self.id}' def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return str(self.id) def get_cost(self): return self.price * self.quantity forms.py class OrderCreateForm(forms.ModelForm): class Meta: model = Order fields = ['address', 'postal_code', 'city'] views.py def order_create(request): cart = Cart(request) if request.method == 'POST': user = request.user form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) context = { 'order': order, } # clear the cart cart.clear() return render(request, 'order/created.html', context) else: form = OrderCreateForm() context = {'cart': cart, 'form': form, } return render(request, 'order/create.html', context) … -
How to use FCM pkg on Django?
I'm using the fcm_django package to send notifications API to Firebase but I have some confusion about those two concepts on Firebase like so: (registeration_id and device_id) https://fcm-django.readthedocs.io/en/latest/#setup I placed the "server_key" of Firebase to registration_id but don't understand what does device_id means and what is the value I should put on it? after answering the above questions I tried to send notification from Django by the admin page on Django by creating registration_id which is "server_key" and defining the type which is a "web", but when I created this object I didn't see any message has been sent to Firebase cloud. Note:- I want to send notifications to only one device not many users. so, can anyone help me to achieve this mission succeeded? Thanks in advance -
How i can fetch fields from models and calculate some filed and pass them to my template?
my model.py class Main(models.Model): name= .... amount = models.PositiveIntegerField(default=40000) In my views: def mainf(request): listmain = models.Main.objects.all() for data in listmain: value = data.amount * 5 calculated_data = data_and_value context = {'main':calculated_data} return render(request,'main/main.html',context) How i can fetch fields from models and calculate some fileds and pass them(calculated_data) to my template? -
How to predefine value inside model/form in Django?
I'm creating simple app which allows users to create group. When user create group it has following fields: name desc inviteKey - i would this field to be hidden and generate 10 characters code and then send it. My models: class Group(models.Model): groupName = models.CharField(max_length=100) description = models.CharField(max_length=255) inviteKey = models.CharField(max_length=255) class Members(models.Model): userId = models.ForeignKey(User, on_delete=models.CASCADE) groupId = models.ForeignKey(Group, on_delete=models.CASCADE) isAdmin = models.BooleanField(default=False) Form: class GroupForm(forms.ModelForm): groupName = forms.CharField(label='Nazwa grupy', max_length=100) description = forms.CharField(label='Opis', max_length=255) inviteKey: forms.CharField(label='Kod wstępu') class Meta: model = Group fields = ['groupName', 'description', 'inviteKey' ] View: def createGroup(request): if request.method == "POST": form = GroupForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Group created') return redirect('/') else: inviteKey = generateInviteKey() form = GroupForm(initial={'inviteKey': inviteKey}) return render(request, 'group/createGroup.html',{'form': form}) Now i have form and inviteKey is visible and editable. I want this key to be visible but not editable. -
I can't verify jwt-token
enter image description here I use drf-jwt : https://styria-digital.github.io/django-rest-framework-jwt/ i made token def jwt_login(user: User): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) return token and User model here class User(AbstractUser): username = None email = models.EmailField(unique=True, db_index=True) secret_key = models.CharField(max_length=255, default=get_random_secret_key) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: swappable = 'AUTH_USER_MODEL' @property def name(self): if not self.last_name: return self.first_name.capitalize() return f'{self.first_name.capitalize()} {self.last_name.capitalize()}' And Urls path('api-jwt-auth/', verify_jwt_token), path('api-jwt-auth/2', obtain_jwt_token), path('api-jwt-auth/3', refresh_jwt_token), And Settings JWT_EXPIRATION_DELTA_DEFAULT = 2.628e+6 # 1 month in seconds JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta( seconds=env.int( 'DJANGO_JWT_EXPIRATION_DELTA', default=JWT_EXPIRATION_DELTA_DEFAULT ) ), 'JWT_AUTH_HEADER_PREFIX': 'JWT', 'JWT_GET_USER_SECRET_KEY': lambda user: user.secret_key, 'JWT_RESPONSE_PAYLOAD_HANDLER': 'pick_restful.selectors.jwt_response_payload_handler', 'JWT_AUTH_COOKIE': 'jwt_token', 'JWT_AUTH_COOKIE_SAMESITE': 'None' } I got jwt-token But I can't verify this token in /api-jwt-auth/ this error what's wrong? -
AttributeError: type object has no attribute 'get_extra_actions'
I have a small web app, and I'm trying to develop an API for it. I'm having an issue with a model I have called Platform inside of an app I have called UserPlatforms. The same error: AttributeError: type object 'UserPlatformList' has no attribute 'get_extra_actions' models.py: class Platform(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='platform_owned', on_delete=models.CASCADE, default=10) PLATFORM_CHOICES = [platform_x, platform_y] platform_reference = models.CharField(max_length=10, choices=PLATFORM_CHOICES, default='platform_x') platform_variables = models.JSONField() api/views.py from .serializers import PlatformSerializer from rest_framework import generics, permissions from userplatforms.models import Platform class UserPlatformList(generics.ListCreateAPIViewAPIView): queryset = Platform.objects.all() permisson_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = PlatformSerializer api/serializer.py from rest_framework import serializers from userplatforms.models import Platform class PlatformSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Platform fields = '__all__' api/urls.py from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'userplatforms/', views.UserPlatformList, 'userplatforms') router.register(r'userfiles/', views.UserFileList, "userfiles") router.register(r'users/', views.UserList, "user") urlpatterns = [ path("^", include(router.urls)) ] -
How to use initial in a form with multiple objects without getting MultipleObjectsReturned Error
Why is form throwing me an exception of MultipleObjectsReturned, when trying to let users edit their profile cover, I have a model for account and i also created a separate model to hold the upload of users profile cover images given that users can have multiple upload of a profile cover images. but somehow i happen to get this error (get() returned more than one AccountCover -- it returned 2!) when upload is more than one cover image. cover = get_object_or_404(AccountCover, account=account.id).first() if request.user: forms = CoverImageForm(request.POST, request.FILES,instance=cover, initial = { 'cover_image':cover.cover_image.url, }) if forms.is_valid(): data = forms.save(commit=False) data.account = cover.account data.save() else: forms = CoverImageForm( initial = { 'cover_image':cover.cover_image, } ) Here is my model for cover image . class AccountCover(models.Model): account = models.ForeignKey(Account,on_delete=models.CASCADE) cover_image = models.ImageField(upload_to=get_cover_image_path,blank=True, null=True) Form for the coverimage class CoverImageForm(forms.ModelForm): class Meta: model = AccountCover fields = ['cover_image'] -
Django Optional Parameters with Django Path method
I am trying to call the same method with a multiple URL (one without parameter). When I call the function it get called multiple time with parameter pk=None. Is there is any way to fix this or why to use an optional parameter with path method in Django here I am providing my code Urls.py path('category/<str:pk>/', CategoryView.as_view(), name="category"), path('category/', CategoryView.as_view(), name="category"), views.py class CategoryView(View): TEMPLATES_NAME = 'home/category.html' def get(self, request,pk=None): base_category = BaseCategory.objects.filter(is_active=True) category_list = Category.objects.filter(is_active=True) if pk is not None: slug=pk if BaseCategory.objects.filter(slug=slug, is_active=True).exists(): return render(request,self.TEMPLATES_NAME,{'base_category':base_category,'category_list':category_list ,'slug':slug}) else: raise PermissionDenied() return render(request,self.TEMPLATES_NAME,{'base_category':base_category,'category_list':category_list}) def post(self, request): return render(request,self.TEMPLATES_NAME) logs Forbidden (Permission denied): /category/null/ Traceback (most recent call last): File "/home/hrishi/.virtualenvs/orgved/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/hrishi/.virtualenvs/orgved/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/hrishi/.virtualenvs/orgved/lib/python3.10/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/hrishi/.virtualenvs/orgved/lib/python3.10/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/home/hrishi/Desktop/Django Projects/orgved/apps/home/views.py", line 95, in get raise PermissionDenied() django.core.exceptions.PermissionDenied [16/Dec/2021 16:03:41] "GET /category/null/ HTTP/1.1" 200 3368 [16/Dec/2021 16:03:41] "GET /category/ HTTP/1.1" 200 35368 -
Comment résoudre cette erreur dans Django?
Lorsque je lance mon serveur local cette erreur est générée: from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' (C:\Users\Administrateur\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\urls_init_.py) -
Serving statics while on FORCE_SCRIPT_NAME
I'm struggling with serving static files while using apache2 proxy. I want to keep my django server on foo path like below. <VirtualHost *:80> ProxyPreserveHost On ProxyPass /foo/ http://0.0.0.0:8000/ ProxyPassReverse /foo/ http://0.0.0.0:8000/ </VirtualHost> With this settings my application is not getting static files e.g. admin site. My app doesn't throw any errors but in my browser i got: Failed to load resource: the server responded with a status of 404 (Not Found) I tried to proxy static <VirtualHost *:80> ProxyPreserveHost On ProxyPass /foo/ http://0.0.0.0:8000/ ProxyPassReverse /foo/ http://0.0.0.0:8000/ ProxyPass /static/ http://0.0.0.0:8000/static/ ProxyPassReverse /static/ http://0.0.0.0:8000/static/ </VirtualHost> And now all I get is: [16/Dec/2021 10:54:14] "GET /api/ HTTP/1.1" 200 5763 [16/Dec/2021 10:54:14] "GET /static/rest_framework/css/bootstrap.min.css HTTP/1.1" 404 1949 [16/Dec/2021 10:54:14] "GET /static/rest_framework/css/bootstrap-tweaks.css HTTP/1.1" 404 1958 [16/Dec/2021 10:54:14] "GET /static/rest_framework/js/jquery-3.5.1.min.js HTTP/1.1" 404 1952 I ran python manage.py collectstatic and my settings.py are: DEBUG = True STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' FORCE_SCRIPT_NAME = '/foo' If I leave my proxy on / everything works fine. Is there any solution or another approach to keep my django app on path and still getting statics? -
AttributeError: 'list' object has no attribute '_committed', Django restframework
I am new to Django in my project, I have to fetch multiple images from a post request. I am doing that using only views.py, I do not use serializers, but I am getting the following Error: AttributeError: 'list' object has no attribute '_committed'. the json structure is like following: { "images":{ "country":[ { "location":"image" }, { "location":"image" } ], "hotel":[ { "location":"image" } ], "room":[ { "location":"image" } ], "bed"[ { "location":"" } ] } } In my views.py: images = data["images"] for country_image in images: country_image_obj = CountryPicture(country=country_obj, location=images["country_images"], ) country_image_obj.save() # hotel images hotel_images = images["hotel"] for hotel_image in hotel_images: hotel_image_obj = HotelPicture(hotel=hotel_obj, location=hotel_image["hotel_images"], ) hotel_image_obj.save() # room images room_images = images["room"] for room_image in room_images: room_image_obj = RoomPicture(room=room_obj, location=room_image["room_images"], ) room_image_obj.save() # bed images bed_images = images["bed"] for bed_image in bed_images: bed_image_obj = BedPicture(bed=bed_obj, location=bed_image["bed_images"], ) bed_image_obj.save() my model.py: class CountryPicture(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, blank=True) location = models.ImageField(upload_to='images/') class HotelPicture(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, null=True, blank=True) location = models.ImageField(upload_to='images/') class RoomPicture(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, null=True, blank=True) location = models.ImageField(upload_to='images/') class BedPicture(models.Model): bed = models.ForeignKey(Bed, on_delete=models.CASCADE, null=True, blank=True) location = models.ImageField(upload_to='images/') -
Alpine Docker Image Problem For Django with MySQL Database
I'm trying to compress the alpine docker image for Django with MYSQL database. But keep getting NameError: name '_mysql' is not defined I have got the Django with Postgres image to 100MB and its working. But with MySQL, the minimum I am able to get is around 500 with non-multi stage builds. -
django rest_framework login system [closed]
I'm using Django and djangorestframework library to make a simple login system in which I get an authentication token if everything is right, but when I'm testing it with Postman, it only accepts the credential when they are in the body section. My questions are: Is this the right thing to send these pieces of information in the body section? If not, how can I change Django to accept these fields in the header section? Also where should I put the authentication token for future uses? (Header or Body) Thank you in advance. -
Get Subscription ID of a PayPal subscription with a trial period
I need to implement a system in which users will have a trial period in their subscription and after that period the user should resume their subscription, I have achieved the same but when a user needs to be deleted the subscription has to be terminated for that when i researched I got an API to cancel a subscription via https://api-m.sandbox.paypal.com/v1/billing/subscriptions/I-BW452GLLEG1P/cancel where I-BW452GLLEG1P in the above is the subscription id, but I don't get a subscription id when I create a subscription via the method suggested on the reference page https://developer.paypal.com/docs/business/subscriptions/customize/trial-period/ please share your thoughts if you encountered similar issues thanks -
Django Serialize a field from a different model
I've 3 models like this: class Category(ClassModelo): description = models.CharField( max_length=100, unique=True ) class SubCategory(ClassModelo): pk_category = models.ForeignKey(Category, on_delete=models.CASCADE) description = models.CharField( max_length=100, ) class Product(ClassModelo): code = models.CharField( description = models.CharField(max_length=200) pk_subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE ) and I'd like to serialize the field description in Category Model, I've tried with the below code but it doesn't work (category = serializers.ReadOnlyField(source='pk_subcategory__pk_category_description'): class ProductsSerializer(serializers.ModelSerializer): subcategory = serializers.ReadOnlyField( source='pk_subcategory.description') category = serializers.ReadOnlyField(source='pk_subcategory__pk_category_description') class Meta: model = Product fields = ("id", "description", "category", "subcategory") -
Django Membership Site
Please, what's the easiest way to implement membership functionality in Django and integrate it with Stripe/Paypal? I tried looking into using Groups but still can't figure out how this work either. Any info and/or suggestion(s) would be greatly appreciated. -
install multiple apps by one entry in INSTALLED_APPS in django (dependency)
is the concept of dependencies available in Django apps too? For example, let's say I'm building my own custom Django app "polls" that can be reused in any Django project. so whenever you need to add it to a project, you will have to add INSTALLED_APPS = [ ... 'polls.apps.PollsConfig', ] but let's also say, that this polls app depends on the Django REST Framework, so whenever you use it, you will have to add that as well INSTALLED_APPS = [ ... 'polls.apps.PollsConfig', 'rest_framework', ] And how about if it depends on even way more apps, do I have to list them all again in the settings.py of each and every project? Or, is there some way to add rest_framework as an installed app inside the apps.py of the polls app so that it's automatically installed whenever polls is installed on a project? -
Django custom user admin login session is not created
I have used a custom user model as auth user model. But while trying to login as admin in the Django admin site. The user is getting authenticated and added to the request.user but session is not created and when it redirects I guess the request.user is lost because it shows EmptyManager object. -
MSSQL - DISTINCT ON fields is not supported by this database backend
I have this form class FromToForm(Form): ModelChoiceField(queryset=TblWorkPlace.objects.all().distinct('work_place_name')) Django writes this error message: DISTINCT ON fields is not supported by this database backend Is there some workaround? -
Django: How to make form conditional?
I have a form with two fields. The user should be required to only select one of the two. Not both and not none. I tried solving this by overwriting the clean method as described in the Django Doc: forms.py class ConfigureWorkout(forms.Form): first_exercise = forms.ModelChoiceField(empty_label="select", label="Choose First Exercise", queryset=FirstExercise.objects.all(), required=False) sec_exercise = forms.ModelChoiceField(empty_label="select", label="Choose Sec Exercise", queryset=SecExercise.objects.all(), required=False) def clean(self): first_exercise = self.cleaned_data.get("first_exercise") sec_exercise = self.cleaned_data.get("sec_exercise") if first_exercise and sec_exercise: raise forms.ValidationError("Enter either a First Exercise or a Secondary Exercise.") else: return self.cleaned_data views.py def configure(request): configure_workout = ConfigureWorkout() if request.method == "GET": return render(request, "userprofile/some.html", configure_workout) else: return render(request, "app/other.html") template <form action="{% url 'configure' %}" method="POST"> {% csrf_token %} {{ configure_workout }} <input type="submit" name="configuration_completed"> </form> However, if I test this by selecting both fields in the form, there won't be an error displayed/raised. I pass the form successfully and get sent to "other.html". What am I missing? Thanks so much in advance for any help :) -
When I ran all my tests in a class I get empty database?
Problem: when I client the main green button to execute all the tests the print(x) returns [3,4]. But, when I click test_block_coaches button the print(x) returns [1,2]. I think the problem is when django delete some the delete data it does not start from a fresh database but it act like the deltion part of the test and keep counting the ides. class TestDataBase(TestClass): def setUp(self, *args, **kwargs): super().setUp(*args, **kwargs) x = PlayerFootballStat.objects.create(height=11, player=self.Player) y = PlayerFootballStat.objects.create(height=13, player=self.Player_2) def test_block_coaches(self): x = [i.id for i in Coach.objects.all()] print(x) -
Django app in Azure - OperationalError at /edit_profile/ (1366, "Incorrect string value: '\\xC5\\x9B' for column 'first_name' at row 1")
I have Django app hosted on Azure that is connected to MySQL database (Azure Database for MySQL). I wanted to edit my profile so I put ść (for testing purposes) in First name and I got the following error: OperationalError at /edit_profile/ (1366, "Incorrect string value: '\\xC5\\x9B\\xC4\\x87' for column 'first_name' at row 1") Request Method: POST Request URL: http://127.0.0.1:8000/edit_profile/ Django Version: 3.2 Exception Type: OperationalError Exception Value: (1366, "Incorrect string value: '\\xC5\\x9B\\xC4\\x87' for column 'first_name' at row 1") Traceback Switch to copy-and-paste view C:\Users\myname\Anaconda3\lib\site-packages\django\db\backends\utils.py, line 84, in _execute return self.cursor.execute(sql, params) … ▶ Local vars C:\Users\myname\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py, line 73, in execute return self.cursor.execute(query, args) … ▶ Local vars C:\Users\myname\Anaconda3\lib\site-packages\MySQLdb\cursors.py, line 206, in execute res = self._query(query) … ▶ Local vars C:\Users\myname\Anaconda3\lib\site-packages\MySQLdb\cursors.py, line 319, in _query db.query(q) … ▶ Local vars C:\Users\myname\Anaconda3\lib\site-packages\MySQLdb\connections.py, line 259, in query _mysql.connection.query(self, query) … ▶ Local vars The above exception ((1366, "Incorrect string value: '\\xC5\\x9B\\xC4\\x87' for column 'first_name' at row 1")) was the direct cause of the following exception: C:\Users\myname\Anaconda3\lib\site-packages\django\core\handlers\exception.py, line 47, in inner My server parameners on Azure are: character_set_server = utf8mb4 (utf8 is not working too) collation_server = utf8_general_ci From what I know Django uses utf-8 by default so my question is what can I … -
Django form fields to HTML
I'm crating fields in a for loop and storing them in a list in a Django form. When trying to place the fields in the HTML file, it appears to be printing the object. Something like this: <django.forms.fields.IntegerField object at ...> My HTML looks like this: {% for i in form.list %} {{i}} {% endfor %} How can I convert that string to an actual input?