Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make Dropdown with input field in django form
I am a noob to django and python 😥 I have a django form, it needs a dropdown menu with input field to enter the text which is not listed in dropdown. Is there any shortcut method for it? -
Why must I use Function-based views if there is Class-based?
From the Django Documentation In the beginning there was only the view function contract, Django passed your function an HttpRequest and expected back an HttpResponse. This was the extent of what Django provided. Early on it was recognized that there were common idioms and patterns found in view development. Function-based generic views were introduced to abstract these patterns and ease view development for the common cases. The problem with function-based generic views is that while they covered the simple cases well, there was no way to extend or customize them beyond some configuration options, limiting their usefulness in many real-world applications. Class-based generic views were created with the same objective as function-based generic views, to make view development easier. However, the way the solution is implemented, through the use of mixins, provides a toolkit that results in class-based generic views being more extensible and flexible than their function-based counterparts.strong text -
Formset not submitting uploaded picture?
I have a view to allow courses to created by users on my app, which am currently having a challenge uploading a course cover(pic) when users create a new course, when course is created all the fields of the course detail get submitted to the data base except the picture data, why is the picture not being submitted, can some one please help me. as this has been a challenge for me for the past week! This is my view to create a new course!. class OwnerMixin(object): def get_queryset(self): qs = super(OwnerMixin, self).get_queryset() return qs.filter(owner=self.request.user) class OwnerEditMixin(object): def form_valid(self, form): form.instance.owner = self.request.user return super(OwnerEditMixin, self).form_valid(form) class OwnerCourseMixin(OwnerMixin): model = Course fields = ['subject', 'title', 'slug','overview','pic'] success_url = reverse_lazy('courses:manage_course_list') class OwnerCourseEditMixin(OwnerCourseMixin): fields = ['subject', 'title','slug', 'overview','pic'] success_url = reverse_lazy('courses:manage_course_list') template_name = 'manage/module/formset.html' class ManageCourseListView(OwnerCourseMixin,ListView): template_name ='courses/course_list.html' class CourseCreateView(OwnerCourseEditMixin,OwnerEditMixin,CreateView,): pass permission_required = 'courses.add_course' class CourseModuleUpdateView(TemplateResponseMixin, View): template_name = 'manage/module/formset.html' course = None def get_formset(self, data=None,): return ModuleFormSet(instance=self.course,data=data,) def get_form(self, data=None): return RequirementFormset(instance=self.course,data=data) def get_forms(self, data=None): return WhatYouWillLearnFormset(instance=self.course,data=data) def dispatch(self, request, pk): self.course = get_object_or_404(Course,id=pk,owner=request.user) return super(CourseModuleUpdateView, self).dispatch(request, pk) def get(self, request, *args, **kwargs): formset = self.get_formset() form = self.get_form() forms = self.get_forms() return self.render_to_response({'course':self.course, 'formset':formset,'form':form,'forms':forms,}) def post(self, request, *args, **kwargs): formset … -
Update in Nested serializer. not turning off validators. E: this slug already exists
I've made a nested serializers which has slugs in both models. Now I learn that in order to be able to do the update on (unique=True) I need to turn off the validator. But somehow I can't seem to turn it off and it'S still throwing the same error. Any way I should be approaching on this problem? serializers.py from rest_framework import serializers from .models import Question, Answer class AnswerSerializer(serializers.ModelSerializer): """Serialize Answer model""" class Meta: model = Answer fields = ('title', 'body', 'slug', 'author', 'question') # https://stackoverflow.com/questions/57249850/overwriting-nested-serializers-create-method-throws-typeerror-create-got-mul read_only_fields = ('question',) lookup_field = 'slug' # https://stackoverflow.com/questions/55031552/how-to-access-child-entire-record-in-parent-model-in-django-rest-framework class QuestionSerializer(serializers.ModelSerializer): """Serialize Question model""" #This answer variable and the fields 'answer' you refer to has to be the SAME but #These can change exp: 'aaa' answer = AnswerSerializer(read_only=False, source='answers', many=True,) class Meta: model = Question fields = ('title', 'body', 'slug', 'author', 'category', 'answer',) lookup_field = 'slug' def create(self, validated_data): answers_data = validated_data.pop('answers') question = Question.objects.create(**validated_data) for answer_data in answers_data: #The above stackoverflow link at the answer serializers is realted to this Answer.objects.create(question=question, **answer_data) return question def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.body = validated_data.get('body', instance.body) instance.slug = validated_data.get('slug', instance.slug) instance.author = validated_data.get('author', instance.author) instance.category = validated_data.get('category', instance.category) instance.save() # https://django.cowhite.com/blog/create-and-update-django-rest-framework-nested-serializers/ answers_data = … -
django celery with multi Q and autoscale
i am try to run celery container in production with autoscale and multi Q as the container entry point as follow **entrypoint.sh** celery -A app worker --autoscale=100,3 -Q mails,index,mixed --loglevel=info but not scaling over 2 workers and only first Q receiving tasks .Also clouds watch log does not shows any logs -
Displaying data from a column of my dataframe in a web page
I want to display the rows of a column of my dataframe in a web page. I get an error on the following line: return render(requete, 'analyse/index.html', context={'data': df['EXTERNAL_DATA2'].tolist()}) below is the error that is displayed: TypeError: list indices must be integers or slices, not str thank you in advance for your help -
How can I get profile picture?
The profile picture is uploading in the database but I can't get the profile picture in the template. How can get the profile picture? Profile Picture View: def change_profile_picture(request): if request.user.is_authenticated: if request.method == "POST": profile_picture = request.FILES['profile_picture'] if 'profile_picture' in request.FILES else None user = get_object_or_404(User, pk=request.user.pk) if request.user.pk != user.pk: messages.success(request,f"{request.user.first_name}, Your profile picture not updated") return redirect("/") Profile_picture.objects.create( Profile_picture = profile_picture, USer = request.user, ) messages.success(request,f"{request.user.first_name}, Your profile picture updated") return redirect("/") return render(request,'0_index.html') Model: class Profile_picture(models.Model): USer = models.ForeignKey(User,default=None,on_delete=models.CASCADE) Profile_picture = models.ImageField(upload_to="3_profile_picture/",null=True, blank=True) def __str__(self): return str(self.pk)+ str(".") + str(self.USer) Template: <form action="change_profile_picture/" method="POST" class="" enctype="multipart/form-data"> {% csrf_token %} <img src="{{ request.user.3_profile_picture }}" alt="" width="100" class="img-fluid rounded-circle mb-3 img-thumbnail shadow-sm"> <input type="file" required name="profile_picture" class="profile_picture_upload"> <button class="btn profile_picture_submit_btn" type="submit">submit</button> </form> -
Unable to create process using 'C:\Users\ibsof\AppData\Local\Microsoft\WindowsApps\python.exe manage.py runserver'
I'm trying to use runserver command over pycharm code terminal. But now it is giving me the error. " Unable to create process using Unable to create process using 'C:\Users\ibsof\AppData\Local\Microsoft\WindowsApps\python.exe manage.py runserver' . But I have the python interpreter in my environment path. Also, I have my virtual environment which I created while initiating the project but still and using the interpreter in my environment I was getting the same error.. -
Why I am getting a single array object instead of all array values in Django rest framework?
I am using Django rest framework for API and pandas to parse excel file. But my Django model takes only the last row of excel file and returns it. I want all rows to be posted and returned. Here is my code. models.py class BusinessImpact(models.Model, ModelWithCreateFromDict): client = models.ForeignKey( accounts_models.Client, on_delete=models.CASCADE) business_process = models.ForeignKey( BusinessProcess, on_delete=models.CASCADE) hierarchy = models.CharField(max_length=255) business_assets = models.CharField(max_length=255) asset_name = models.CharField(max_length=255) vendors = models.CharField(max_length=255) product = models.CharField(max_length=255) version = models.CharField(max_length=10) cpe = models.CharField(max_length=255) asset_type = models.CharField(max_length=10) asset_categorization = models.CharField(max_length=255) asset_risk = models.CharField(max_length=50) _regulations = models.TextField(blank=True) _geolocation = models.TextField(blank=True) def __str__(self) -> str: return self.hierarchy + " - " + self.business_assets @property def regulations(self) -> List[str]: return self._regulations.split(",") @property def geolocation(self) -> List[str]: return self._geolocation.split(",") excel_titles = { "hierarchy": "Hierarchy", "business_assets": "Business Assets", "asset_name": "Asset Name", "vendors": "Vendors", "product": "Product", "version": "Version", "cpe": "CPE", "asset_type": "Asset Type", "asset_categorization": "Asset Categorization", "asset_risk": "Asset Risk", "_regulations": "Regulations", "_geolocation": "GeoLocation", } important_fields = ["hierarchy", "business_assets", "asset_name"] views.py class UploadBusinessImpactExcelByClientAdmin(APIView, ExcelHandlingView): def post(self, request): self.can_model_handle_ExcelHandlingView(models.BusinessImpact) serializer = serializers.ExcelFileAndBusinessProcessUploader( data=request.data) if serializer.is_valid(): data = serializer.validated_data file = data.get("file") client = request.user.client business_process_id = data.get("business_process") try: business_process = get_business_process_by_client( client, business_process_id ) except ( models.BusinessProcess.DoesNotExist, accountModels.Client.DoesNotExist, ) as e: return Response( "business process … -
Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace
I'm a beginner in Django, this is my code: from django.contrib import admin from django.urls import path from django.urls import include, re_path app_name="myproject" urlpatterns = [ path('admin/', admin.site.urls), re_path(r'', include('learning_logs.urls', namespace='learning_logs')) ] I need you guys help!!! I'm having this error....please help me.... 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. -
django multiple image upload
Hi I am pretty new to Django and trying to let the user upload multiple images per project. The Django Documentation enter link description here shows how to do it in generell but I think I am rendering my form differently than they are doing it. So I don´t know how to add the 'multiple' attribute in my input field. In addition they have an extra class in their views.py and inside of that the function. Thanks for your help. views.py def createProject(request): form = ProjectForm() if request.method == 'POST': form = ProjectForm(request.POST, request.FILES) if form.is_valid(): project = form.save(commit=False) project.save() context = {'form':form} return render(request, 'projects/project_form.html', context) models.py class Project(models.Model): title = models.CharField(max_length=200) featured_images = models.ImageField(null=True, blank=True, default="default.jpg") forms.py class ProjectForm(ModelForm): class Meta: model = Project fields = ['title', 'featured_images'] project_form.html <form class="form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} </div> {% endfor %} </form> -
Using a local Django app without packaging it
I'm planning to write an add-on app for an existing django app. The primary app is running smoothly via docker-compose, and I've remoted into the container via the vscode remote-containers extension. Add-ons are installed like most any other django app, pip install APPNAME, append to INSTALLED_APPS, migrate, collectstatic, restart server. I can create a directory anywhere in the container, where the add-on will exist and be developed, but I'm looking for a way to make the app visible from that directory so I can include it in the primary app's INSTALLED_APPS list. Is this possible, or would I have to create the app inside the primary package's site-packages directory alongside its own sub-apps for this to work? -
expected bytes or bytearray, but got 'NoneType' in Django
I recieve a response from a payment gateway(paystack) and am trying to verify that events originate from Paystack to avoid delivering value based on a countefeit event. I have the error below anytime i get the respone from them raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__) TypeError: key: expected bytes or bytearray, but got 'NoneType' Views.py @require_POST @csrf_exempt def webhook(request): secret = getattr( settings, ' PAYSTACK_PRIVATE_KEY', None ) webhook_data = request.body hash = hmac.new(secret, webhook_data, digestmod=hashlib.sha512).hexdigest() if hash != request.headers["HTTP_X_PAYSTACK_SIGNATURE"]: raise ValidationError("MAC authentication failed") response_data = json.loads(request.body) return HttpResponse(status=200) You can take a look at the paysatck API webhook doc here: https://paystack.com/docs/payments/webhooks/#verifying-events -
Restricting view by model permissions fails in django
Very basically I have a model member and want to restrict searching members to allowed users. I use the following in the corresponding view if request.user.has_perm('view_member'): context['user_list'] = get_user(q) Sadly this does not work even if a) I give a user this permission via the admin interface b) in my tests that look a bit like the following def test_user_search_view(self): self.client.login(username='testuser0', password='12345') # this is a user that was given the permission (see below) response = self.client.post(reverse('library:search'), data={'q': "Müller"}) # Check our user is logged in self.assertEqual(str(response.context['user']), 'testuser0') # Works self.assertContains(response, "Max") # Fails, but max shouls be there For further tests I used the debugging mode of PyCharm to go into the test. In the console I then executed the following >>> permission_view_user = Permission.objects.get(codename='view_member') >>> test_user0.user_permissions.add(permission_view_user) >>> test_user0.save() # For good luck >>> user = get_object_or_404(User, pk=test_user0.pk) >>> user.has_perm(permission_view_user) False I would expect true here. -
How can i get 'pk' or 'id' in get_context_data from ListView
How can i get 'pk' or 'id' in get_context_data from ListView class AllListView(ListView): context_object_name = 'all_products' queryset = Product.objects.all template_name = 'jewelry_store/home.html' def get_context_data(self,**kwargs): context = super(AllListView,self).get_context_data(**kwargs) context['collections'] = Collection.objects.all context['products'] = self.queryset context['cool'] = Collection.objects.filter(pk=self.kwargs.get('pk')) in output it gives empty queryset in urls path('', views.AllListView.as_view(), name='all_products') `` -
Queryset for mutiple table joins
class Organization(models.Model): """Organization Model""" name = models.CharField(max_length=100, blank=False) is_active = models.BooleanField(default=True) class Department(models.Model): """Department Model""" org = models.ForeignKey(Organization, on_delete=models.PROTECT, related_name='Department_Org') name = models.CharField(max_length=100, blank=False) is_active = models.BooleanField(default=True) class Project(models.Model): """Project Model""" dept = models.ForeignKey(Department, on_delete=models.PROTECT, related_name='Project_Dept', null=True) no = models.CharField(max_length=100, blank=False) name = models.CharField(max_length=255, blank=True) is_active = models.BooleanField(default=True) class Subscription(models.Model): """Subscription Model""" MODULE_CHOICES = ( ('ECM', 'Change Management'), ('DMS', 'Document Management'), ('AIM', 'Deviation Management'), ('PMS', 'Project Management'), ('ADM', 'Admin'), ('RPT', 'Reports'), ('MTS', 'My Tasks'), ) project = models.ForeignKey(Project, on_delete=models.PROTECT, related_name='Subscription_Project') module = models.CharField(max_length=3, choices=MODULE_CHOICES) class User(AbstractBaseUser, PermissionsMixin): """Custom User Model""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) displayname = models.CharField(max_length=255, blank=True) fname = models.CharField(max_length=255, blank=True) lname = models.CharField(max_length=255, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) class UserProjectSubscriptionRole(models.Model): """User Role Model""" user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='UserProjectRole_user') project = models.ForeignKey(Subscription, on_delete=models.PROTECT, related_name='UserProjectRole_Module') role = models.ForeignKey(RoleType, on_delete=models.PROTECT, related_name="UserProjectRole_role") I need to write queryset to get Organizations to which User is associated. -
WebGL Build(Unity) does not work when Debug = False in Django
I'm having some trouble in serving the page on which Unity's WebGL build is embedded in my Django Website. It works fine when Debug is set to True in settings.py. But when Debug is set to False. It gives me Server Error 500. I've searched on this and people are saying that the build size must've been larger than 100MB. But The build size is only 6.66 MB. Here's my settings.py import os from pathlib import Path import django_heroku import dj_database_url from decouple import config BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'users.apps.UsersConfig', 'viewer.apps.ViewerConfig', 'rest_framework' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # Cors Headers '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', 'whitenoise.middleware.WhiteNoiseMiddleware', # WhiteNoise ] ROOT_URLCONF = 'UnityPlus.urls' CORS_ORIGIN_ALLOW_ALL=True 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 = 'UnityPlus.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/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', … -
What is the easiest way to reset migrations in heroku CLI?
I recently deployed django rest api project on heroku and I wanted to remove migrations and migrate again. I have tried heroku run python manage.py migrate --app cyberminds-backend zero but it returns CommandError: No installed app with label 'zero' What are the easiest steps or commands to achieve this? Thanks -
Invalid object name - statements could not be prepared
I have built a custom user model which until introducing database routers was working fine. I have pasted the model below and wondered if anyone had any insight as to why it is generating the following sql error message. django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'Users2_customuser'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") import datetime from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from django.core.mail import send_mail from django.utils.translation import ugettext_lazy as _ import logging log = logging.getLogger(__name__) class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): if not email: raise ValueError(_(f'Please enter an email address')) email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save() log.info(f'User created with email: {email}') return user def create_superuser(self, email, password=None, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) if kwargs.get('is_staff') is not True: raise ValueError(f'Superuser must have staff permission') if kwargs.get('is_superuser') is not True: raise ValueError(f'Superuser must have superuser permission') log.info(f'Superuser created with email: {email}') return self.create_user(email, password, **kwargs) class CustomUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150, blank=True) surname = models.CharField(max_length=150, blank=True) address1 = models.CharField(max_length=254, blank=True) address2 = models.CharField(max_length=254, blank=True) area_code = models.CharField(max_length=20, … -
DRF simplejwt do not updating the access token
I'm using simpleJWT with Django restframework and i get this problem when i tried to refresh the access token, i post http request sending the refresh token to the refresh endpoint, it suppose to get new access, but i keep getting the same access token even though the access token has expired ! what's reason that might cause this ? is there anyone can help please ? setting.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer'), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=1), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } urls.py from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] -
How to make add to cart without reloading the page (js and django)?
Im making this add to cart functionality, and I want to show the new cart total after adding to cart without reloading the page. Right now I have it to reload the page to show the cart changes after having added a product. (SOME OF THE CODE CAN BE IN DANISH, I HOPE ITS FINE) HTML (The add to cart button) <div class="buy-item flex flex-ai-c"> <button data-product="{{product.id}}" data-action="add" class="add-button add-btn update-cart">TILFØJ TIL KURV</button> <div class="flex flex-ai-c flex-jc-c"> <span class="cart-quantity-text">ANTAL</span> <input class="cart-quantity-input" type="number" value="1"> </div> </div> JS function addCookieItem(productId, action) { if(action == 'add'){ if(cart[productId] == undefined){ cart[productId] = {'quantity':parseInt(antal.value)} }else{ cart[productId]['quantity'] += parseInt(antal.value) } } if(action == 'add-from-cart'){ cart[productId]['quantity'] += 1 } if(action == 'remove-from-cart'){ cart[productId]['quantity'] -= 1 if(cart[productId]['quantity'] <= 0){ console.log('Remove Item') delete cart[productId] } } if(action == 'delete'){ delete cart[productId] } console.log('Cart:', cart) document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/" location.reload() } Django def cookieCart(request): try: cart = json.loads(request.COOKIES['cart']) except: cart = {} print('Cart:', cart) items = [] order = {'get_cart_total':0, 'get_cart_items':0} cartItems = order['get_cart_items'] for i in cart: try: cartItems += cart[i]['quantity'] product = Product.objects.get(id=i) total = (product.price * cart[i]['quantity']) order['get_cart_total'] += total order['get_cart_items'] += cart[i]['quantity'] item = { 'product':{ 'id':product.id, 'name':product.name, 'price':product.price, 'imageURL': product.imageURL, 'stripe-price': product.stripe_price_id, … -
Django ManyToMany CheckConstraint IntegerField
I have some models, 1 abstract, and 2 that inherit from the abstract model with a ManyToMany relationship. One model gets its members from the other model. I want to implement a constraint on this model so that its members can't be more than the Sum of the remaining_members on the original groups. I created a Q expression that expresses what I want to achieve, but I know it's not the right way to do it. How can I create the constraint with models that are related by a ManyToMany field? class AbstractGroup(models.Model): members = models.IntegerField() class Meta: abstract=True class OriginalGroup(AbstractGroup): remaining_members = models.IntegerField() new_group_members = ManyToManyField(NewGroup, related_name=new_group, related_query_name=new_group) class NewGroup(AbstractGroup): name = models.CharField() class Meta: constraints = [ models.CheckConstraint( Q(members__lte=original_groups__sum__remaining_members, name='%(app_label)s_%(class)s_available_members' ) ) ] -
How do I recommit database to Heroku after destroying DB in the Heroku dashboard
I've built an app using Django etc. I ran into a whole bunch of problems with database on Heroku after accidentally pushing to production before running heroku run python manage.py makemigrations and heroku run python manage.py migrate. I decided to just completely destroy the database currently on Heroku and want to recommit my app's models to heroku. My hope is to completely start from a clean slate. I just want to make sure I do this correctly so I'm asking for clear instructions about how to recommit my app's database to Heroku after destroying the database in the dashboard. Current error I get when I open my app online is: settings.DATABASES is improperly configured. Please supply the NAME or OPTIONS['service'] value. Thanks! -
Why Django rest framework is not saving data but returns 200 ok code
I have successfully send a post request to deployed(in Heroku) Django rest API from react axios but the data is not saved in my database. I use MongoDB(Djongo) as a databse. Let me show you the code I have used. settings.py """ Django settings for CyberMinds project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "rest_framework.authtoken", "corsheaders", "accounts", "threat_catalog_models", 'django_rest_passwordreset', "threat_catalog", # "risk_model", "risk_model", "business_process", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "config.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "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 = "config.wsgi.application" # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { "default": { "ENGINE": "djongo", "NAME": "cyberminds", } … -
Failed to execute command: No such file or directory (Gunicorn) (Django)
First I have created a socket named 'receiver.socket' (nvenv) papli@sender:/datadrive/receiver/GisServer$ cat cat /etc/systemd/system/receiver.socket cat: cat: No such file or directory [Unit] Description=receiver socket [Socket] ListenStream=/run/receiver.sock [Install] WantedBy=sockets.target Then, I created a service file with the same name 'receiver.service' (nvenv) papli@sender:/datadrive/receiver/GisServer$ cat /etc/systemd/system/receiver.service [Unit] Description=gunicorn daemon Requires=receiver.socket After=network.target [Service] User=papli Group=papli RuntimeDirectory=gunicorn WorkingDirectory=/datadrive/receiver/GisServer Environment="PATH=/datadrive/receiver/GisServer/nvenv/bin" ExecStart=/datadrive/receiver/GisServer/nvenv/bin/gunicorn --access-logfile /datadrive/sender/log/gunicorn.log --workers 3 --bind unix:/run/receiver.sock GisServer.wsgi:application [Install] WantedBy=multi-user.target After that sudo systemctl enable receiver sudo systemctl start receiver Error that I am getting (nvenv) papli@sender:/datadrive/receiver/GisServer$ sudo systemctl status receiver ● receiver.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/receiver.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sat 2022-03-19 07:14:09 UTC; 3min 38s ago Main PID: 6029 (code=exited, status=203/EXEC) Mar 19 07:14:09 sender systemd[1]: Started gunicorn daemon. Mar 19 07:14:09 sender systemd[6029]: receiver.service: Failed to execute command: No such file or directory Mar 19 07:14:09 sender systemd[6029]: receiver.service: Failed at step EXEC spawning /datadrive/receiver/GisServer/nvenv/bin/gunicorn: No Mar 19 07:14:09 sender systemd[1]: receiver.service: Main process exited, code=exited, status=203/EXEC Mar 19 07:14:09 sender systemd[1]: receiver.service: Failed with result 'exit-code'. Troubleshooting Steps I followed Checked sock file is created. (nvenv) papli@sender:/datadrive/receiver/GisServer$ ls /run/receiver.sock /run/receiver.sock Inside nvenv/bin gunicorn file is present and their permissions are adequate (nvenv) papli@sender:/datadrive/receiver/GisServer$ ls -la nvenv/bin/gunicorn …