Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Amazon-pay-sdk-python CreateButtonSignature
I'm integrating amazon-pay-SDK-python for the web. I have done reading all documentation of amazon-pay, but I didn't get any idea about how to give or create a button signature in Frontend/backend code. Here is my code of frontend to create a button of amazon-pay One-time-checkout. If anyone implemented this, give your valuable answer.. <body> <div id="AmazonPayButton"></div> <script src="https://static-na.payments-amazon.com/checkout.js"></script> <script type="text/javascript" charset="utf-8"> amazon.Pay.renderButton('#AmazonPayButton', { // set checkout environment merchantId: 'merchant_id', publicKeyId: 'SANDBOX-xxxxxxxxxx', ledgerCurrency: 'USD', // customize the buyer experience checkoutLanguage: 'en_US', productType: 'PayAndShip', placement: 'Cart', buttonColor: 'Gold', // configure Create Checkout Session request createCheckoutSessionConfig: { payloadJSON: 'payload', // string generated in step 2 signature: 'xxxx' // signature generated in step 3 } }); </script> </body> -
code H10 while Deploying Django code to Heroku
2021-12-16T14:04:17.499957+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=phoneinf0.herokuapp.com request_id=4b00137c-bb8e-426d-b427-fff468ac7491 fwd="94.249.24.198" dyno= connect= service= status=503 bytes= protocol=https -
how to display data of that date of week. which data is exist on that day by using python django
I want to return a week data of date, if data is exist on that date from threading. If there is data of that date, it should appear in the data list, and if there is no data of that date then a blank list should appear. currently I have data in database only of 2 days but same data returning on all 7 days. class TotalExceedance(Thread): def __init__(self,site): Thread.__init__(self) self.site = site def run(self): currentDate = datetime.datetime.now().date() weekAgo = currentDate - datetime.timedelta(days=7) site_label = self.site.json()[0]["label"] week_exc_data = [] for i in range(1,8): total_exceedance = ExceedanceModel.objects.filter(site=site_label,dateTime__date__range=[weekAgo, currentDate]).all().values() day = weekAgo + datetime.timedelta(days=i) print(day) week_exce = total_exceedance,day week_exc_data.insert(0, len(week_exce)) print("week exc data :", week_exc_data) #thread start th2 = TotalExceedance(sites) th2.start() th2.join() getting this output : 2021-12-10 2021-12-11 2021-12-12 2021-12-13 2021-12-14 2021-12-15 2021-12-16 week exc data : [2, 2, 2, 2, 2, 2, 2] I am expecting output like this : 2021-12-10 week exc data : [] 2021-12-11 week exc data : [] 2021-12-12 week exc data :[{'dateTime': '2021-12-12T08:55:00Z', 'site': 'ABCP', 'station': 'ABCP_1', 'parameter': 'COD', 'values': 5000.0}] 2021-12-13 week exc data : [] 2021-12-14 week exc data : [] 2021-12-15 week exc data : [{'dateTime': '2021-12-15T08:55:00Z', 'site': 'ABCP', 'station': 'ABCP_1', 'parameter': 'COD', … -
Delete all documents in a MongoDB collection via Django backend and Angular frontend
I have managed to write code to add a customer to my MongoDB collection from my Angular service method to my Django http function, as follows: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json' }), withCredentials: false } @Injectable() export class MongoService { myApiBaseUrl = "http://localhost:8000/mydjangobaselink/"; constructor(private httpClient: HttpClient) { } addCustomer(customerFormInfo: Customer): Observable<Customer> { return this.httpClient.post<Customer>(`${this.myApiBaseUrl}`, JSON.stringify(customerData), httpOptions); } deleteCustomer(): Observable<Customer> { return this.httpClient.delete<Customer>(`${this.myApiBaseUrl}`); } } @csrf_exempt @api_view(['GET', 'POST', 'DELETE']) def handle_customer(request): if request.method == 'POST': try: customer_data = JSONParser().parse(request) customer_serializer = CustomerModelSerializer(data=customer_data) if customer_serializer.is_valid(): customer_serializer.save() # Write customer data to MongoDB. collection_name.insert_one(customer_serializer.data) response = { 'message': "Successfully uploaded a customer with id = %d" % customer_serializer.data.get('id'), 'customers': [customer_serializer.data], 'error': "" } return JsonResponse(response, status=status.HTTP_201_CREATED) else: error = { 'message': "Can not upload successfully!", 'customers': "[]", 'error': customer_serializer.errors } return JsonResponse(error, status=status.HTTP_400_BAD_REQUEST) except: exceptionError = { 'message': "Can not upload successfully!", 'customers': "[]", 'error': "Having an exception!" } return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR) elif request.method == 'DELETE': try: CustomerModel.objects.all().delete() # Delete customer data from MongoDB. collection_name.deleteMany({}) return HttpResponse(status=status.HTTP_204_NO_CONTENT) except: exceptionError = { 'message': "Can not delete successfully!", 'customers': "[]", 'error': "Having an exception!" } return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR) The POST method works fine and I can see the added … -
AttributeError: 'RelatedManager' object has no attribute '' reverse connection
I'm trying to implement reverse connection , but i get this error : 'admin':i.mobileinv_imei.invoice.seller.username, AttributeError: 'RelatedManager' object has no attribute 'invoice' this is my models.py class Imei(models.Model): mobile = models.ForeignKey(MobileCollection,on_delete=models.PROTECT) imei = models.CharField(max_length=15,unique=True) status= models.BooleanField(default=True) class ImeiInvoice(models.Model): item = models.ForeignKey(Imei,on_delete=models.PROTECT,related_name='mobileinv_imei') invoice = models.ForeignKey(CustomerInvoice,on_delete=models.CASCADE,related_name='invoice') price = models.DecimalField(max_digits=20,decimal_places=3) class CustomerInvoice(models.Model): seller = models.ForeignKey(User,on_delete=models.PROTECT) customer = models.CharField(max_length=50) mobiles = models.ManyToManyField(Imei,through='ImeiInvoice') im trying to return seller name from Imei model, here is my views.py def imei_sold_lists(request): imeis = Imei.objects.filter(status=False) lists = [] for i in imeis: imei = { 'admin':i.mobileinv_imei.invoice.seller.username, 'customer':i.mobileinv_imei.invoice.customer, 'imei':i.imei, 'price':i.mobileinv_imei.price } lists.append(imei) return JsonResponse({'data':lists}) is there something i've missed please? or should i change something please? Thank you for helping .. -
PostgreSQL delete record from two joined tables based on conditions
In my django project, with a PostgreSQL database connected i create these two models: class Results(models.Model): device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL) proj_code = models.CharField(max_length=400) res_key = models.SlugField(max_length=80, verbose_name="Message unique key", primary_key=True, unique=True) read_date = models.DateTimeField(verbose_name="Datetime of vals readings") unit = models.ForeignKey(ModbusDevice, null=True, on_delete=models.SET_NULL) class VarsResults(models.Model): id = models.AutoField(primary_key=True) key_res = models.ForeignKey(Results, related_name="keyres", on_delete=models.CASCADE) var_id = models.ForeignKey(ModbusVariable, null=True, on_delete=models.SET_NULL) var_val = models.CharField(max_length=400, blank=True) var_val_conv = models.CharField(max_length=100, blank=True, null=True) base_byte_order = models.CharField(max_length=15) var_hash = models.CharField(max_length=400) has_error = models.BooleanField(default=False) so VarsResults have a Foreignkey to Results, i would delete some records in both table starting from a condition based on Results, for example DELETE RECORDS FROM RESULTS IF RESULTS read_date < VALUE i would to automatically also delete all related records in VarsResults table. Is there a method in django ORM or directly using SQL for achieve this? So many thanks in advance -
How can I send a sms in Django?
I encountered a problem when trying to send sms using the SMSC service in Django project. My Celery task for sending email and sms: def order_created_retail(order_id): # Task to send an email when an order is successfully created order = OrderRetail.objects.get(id=order_id) subject = 'Order №{}.'.format(order_id) message_mail = 'Hello, {}! You have successfully placed an order{}. Manager will contact you shortly'.format(order.first_name, order.id) message_sms = 'Your order №{} is accepted! Wait for operator call' mail_sent = send_mail( subject, message_mail, 'email@email.com', [order.email] ) smsc = SMSC() sms_sent = smsc.send_sms( [order.phone], str(message_sms) ) return mail_sent, sms_sent Email sends correctly, but for sms I get that error: Task orders.tasks.order_created_retail[f05458b1-65e8-493b-9069-fbaa55083e7a] raised unexpected: TypeError('quote_from_bytes() expected bytes') function from SMSC library: def send_sms(self, phones, message, translit=0, time="", id=0, format=0, sender=False, query=""): formats = ["flash=1", "push=1", "hlr=1", "bin=1", "bin=2", "ping=1", "mms=1", "mail=1", "call=1", "viber=1", "soc=1"] m = self._smsc_send_cmd("send", "cost=3&phones=" + quote(phones) + "&mes=" + quote(message) + \ "&translit=" + str(translit) + "&id=" + str(id) + ifs(format > 0, "&" + formats[format-1], "") + \ ifs(sender == False, "", "&sender=" + quote(str(sender))) + \ ifs(time, "&time=" + quote(time), "") + ifs(query, "&" + query, "")) # (id, cnt, cost, balance) или (id, -error) if SMSC_DEBUG: if m[1] > "0": print("Сообщение … -
Performing DELETE call in DRF using axios returns 301
I'm struggling with calling delete on my drf api using axios. Constantly returns 301... I'm having one class based view containing create/list/delete methods. What might be wrong here? axios call: async delete_qr(id){ api.delete("tickets/qr/delete/"+String(id), {headers:{Authorization:'JWT '+this.$store.state.jwt}, data:{pk:id}}) .then(response => { console.log(response.data) this.tickets = response.data }) .catch(error => { console.log(error) }) views.py class TicketApi(CreateAPIView, ModelViewSet): permission_classes = ( permissions.IsAdminUser, permissions.IsAuthenticated, ) authentication_classes = (JSONWebTokenAuthentication,) serializer_class = TicketSerializer queryset = Tickets.objects.all() def destroy(self, request, pk): ticket = self.get_object(pk) self.perform_destroy(ticket) return Response({"info":f"ticket with id {pk} has been deleted"}, status=status.HTTP_200_OK) urls.py router = routers.DefaultRouter() router.register("qr/create", TicketApi, basename="qr_create") router.register("qr/list", TicketApi, basename="qr_list") router.register("qr/delete", TicketApi, basename="qr_delete") -
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")