Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Schema validation failed; XML does not comply with UBL 2.1 standards in line with ZATCA specifications
I am trying to use validate my xml with UBL 2.1 standards in line with ZATCA specifications. But I can't validate that as my xml looking great but I don't understand what's going wrong .I used python json2xml package for creating xml.This package generate xml from json. Erros list what I am getting from ZATCA XML Validator: category : XSD_SCHEMA_ERROR code :SAXParseException message : Schema validation failed; XML does not comply with UBL 2.1 standards in line with ZATCA specifications Here is my Xml code: <?xml version="1.0" ?> <Invoice> <ProfileID>reporting:1.0</ProfileID> <ID>INV004</ID> <UUID>fd5a7cc4-2316-49ee-ac07-6f4be4be3731</UUID> <IssueDate>2022-08-13</IssueDate> <IssueTime>23:46:07</IssueTime> <InvoiceTypeCode>388</InvoiceTypeCode> <InvoiceTypeCodeName>0101001</InvoiceTypeCodeName> <DocumentCurrencyCode>SAR</DocumentCurrencyCode> <TaxCurrencyCode>SAR</TaxCurrencyCode> <Note/> <OrderReference> <ID/> </OrderReference> <ContractDocumentReference> <ID/> </ContractDocumentReference> <AdditionalDocumentReference> <UUID>4</UUID> <PIH> <Attachment> <EmbeddedDocumentBinaryObject>ET05jV7roub7D66wOAQ49TQ8mCkyldhmH7B8CV3Rc6g=</EmbeddedDocumentBinaryObject> </Attachment> </PIH> <QR> <Attachment> <EmbeddedDocumentBinaryObject>5D6ZU7f6nb+s1szmMw46l4NZ7yTy0p1wi0ZUMsdQWBE=</EmbeddedDocumentBinaryObject> </Attachment> </QR> </AdditionalDocumentReference> <Signature> <ID>urn:oasis:names:specification: ubl:signature:Invoice</ID> <SignatureMethod>urn:oasis:names:specification:ubl:dsig:enveloped: xades</SignatureMethod> </Signature> <AccountingSupplierParty> <Party> <PartyLegalEntity> <RegistrationName>Altaf Miazee</RegistrationName> </PartyLegalEntity> <PartyIdentification> <ID/> </PartyIdentification> <PartyTaxScheme> <CompanyID>300600363600003</CompanyID> </PartyTaxScheme> <PostalAddress> <Country> <IdentificationCode>BD</IdentificationCode> </Country> <AdditionalStreetName>Altafbari</AdditionalStreetName> <StreetName>dhaka</StreetName> <BuildingNumber>1233</BuildingNumber> <PlotIdentification>1233</PlotIdentification> <CityName>Dhaka</CityName> <PostalZone>12302</PostalZone> <CountrySubentity>Dhaka</CountrySubentity> <CitySubdivisionName>miazee</CitySubdivisionName> </PostalAddress> </Party> </AccountingSupplierParty> <AccountingCustomerParty> <Party> <PartyLegalEntity> <RegistrationName>Hosen MD Altaf</RegistrationName> </PartyLegalEntity> <PartyIdentification> <ID>398765409876333</ID> </PartyIdentification> <PartyTaxScheme> <CompanyID>398765409876333</CompanyID> </PartyTaxScheme> <PostalAddress> <StreetName>الملك سلمان</StreetName> <AdditionalStreetName>الملك سلمان</AdditionalStreetName> <BuildingNumber>1234</BuildingNumber> <PlotIdentification>1234</PlotIdentification> <CityName>dhaka</CityName> <PostalZone>12234</PostalZone> <CountrySubentity>Dhaka</CountrySubentity> <CitySubdivisionName>الملك سلمان</CitySubdivisionName> <Country> <IdentificationCode>BD</IdentificationCode> </Country> </PostalAddress> </Party> </AccountingCustomerParty> <Delivery> <ActualDeliveryDate>2022-08-25</ActualDeliveryDate> <LatestDeliveryDate/> </Delivery> <PaymentMeans> <PaymentMeansCode>10</PaymentMeansCode> <PayeeFinancialAccount> <PaymentNote/> </PayeeFinancialAccount> </PaymentMeans> <AllowanceCharge> <TaxCategory> <ID>S</ID> <Percent>0.0</Percent> <TaxScheme> <ID>VAT</ID> </TaxScheme> </TaxCategory> … -
mutations with one to many relationship graphene_django
i want to add an internships to a specific cv using the id of the cv here is the modles class CV(models.Model): photo = models.ImageField(upload_to='CV/%Y/%m/%d/', null=True) headline = models.CharField(max_length=250) education = models.CharField(max_length=250) employment=models.CharField(max_length=250) class Internships(models.Model): employer=models.CharField(max_length=250) position=models.CharField(max_length=250) internship=models.ForeignKey(CV,on_delete=models.CASCADE) and here is the schema file class Internships(models.Model): employer=models.CharField(max_length=250) position=models.CharField(max_length=250) internship=models.ForeignKey(CV,on_delete=models.CASCADE) class createInternships(graphene.Mutation): class Arguments(): employer=graphene.String(required=True) position=graphene.String(required=True) internship=graphene.Int() internship=graphene.Field(InternshipsType) @staticmethod def mutate(root, info, employer,position): cv_object=CV.objects.get(id=id) internship=Internships.objects.create(employer=employer,position=position,internship=cv_object) return createInternships(internship=internship) and it will be appreciated if someone can also tell me the query i should type to create an internship related to the cv i have already created -
Prepopulate a choice field by a model
Im new to Django development and have a question regarding choice fields. I want to populate a choice field by a model: # function.py [1] ingredients = Ingredients.objects.all() [2] extras = Extras.objects.filter(pizza_id=pizza_id) [3] form = SelectIngredientsForm(extras,ingredients) # forms.py # Note its Form not ModelForm class SelectIngredientsForm(forms.Form): [4] ingredients = forms.ChoiceField(choices=X) [5] extras = forms.ChoiceField(choices=X) My Question is: How can I populate the choices in the Form ([4] and [5]) with the objects I have got previously [3] from object [1] and object [2]? -
Why empty value to instance?
I use django-autocomplete-light. I have a model: class MyModel(models.Model): name = models.CharField( 'MyName', max_length=200, ) city = models.CharField( 'City', max_length=200, ) In my admin: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): list_display = ( 'pk', 'name', ) form = MyModelForm class MyModelForm(forms.ModelForm): class Meta: model = MyModel exclude = [] widgets = auto_widgets_city auto_widgets_city = { 'city': autocomplete.ListSelect2( url='city-autocomplete', ), } In views: class CityAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = City.objects.all() return qs It`s work, but if I save instance with city and when I go to admin/change, field city is empty. Why is it? -
POSTGRESQL - DJANGO - time without time zone en date
I'm working on a project's Django with a Postegresql database. I just created a model like that : from django.db import models from members.models import CustomUser class Article(models.Model): title = models.CharField(max_length=250) body = models.TextField() custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) def __str__(self): return self.title class Meta: ordering = ["-created_at"] def save(self, *args, **kwargs): super().save(*args, **kwargs) When I try to migrate, I've this issue : ERREUR: can't convert type time without time zone en date In my DB, I've in my table "time without time zone". Do you have any ideas ? Thanks ! -
Django + Vue 403 Forbidden Error On axios.get
I'm trying to log the user but the Django rest API can't see the current jwt token of the logging user and I'm getting a 403 error. The API is working fine on the Postman with all the Authentication aspects. I have tried some advised solutions but they don't seem to work. Attempt 1 axios.defaults.headers.common["authorization"] = "Bearer " + localStorage.getItem("jwt"); await axios.get(api-link) Attempt 2 axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; await axios.get(api-link) Attempt 3 await axios.get(api-link.{ { headers:{header stuff} }, {withCredentials: true} ) (Basically adding headers and credentials inside the get request.) Django settings.py I couldn't find a standard for this, currently I'm using this one for testing: 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', 'users', ] 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', ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ['http://127.0.0.1:8000', 'http://localhost:8000'] REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', ] } CSRF_COOKIE_NAME = "XSRF-TOKEN" -
Django environ returns -> Invalid line: SECRET_KEY = "..."
I recently included Django environ and it returns the following notification when starting the development server: Invalid line: SECRET_KEY = "django-insecure-9o9f18*-fk%9dh5s0$4xzt836m)*y!testestyf*z8$=j^uxks)k" All other environment variables work smoothly within my settings.py except for that notification (which doesn't seem to interrupt any processes yet). Any ideas? -
Cant find video downloaded with selenium on Heroku - Django
I have the following application I'm working on but I have an error that I can't figure out what I should do. The application is as follows the user adds a link to a video, the task is sent to celery via redis, celery downloads that video and saves it to media/AppVimeoApp/videos/.mp4, then displays it on a page with src="media\AppVimeoApp\videos....mp4". This app works fine locally, on heroku however the task shows me as successful but the video is nowhere to be found, I just need it temporarily. tasks.py @shared_task def download_video(): chrome_options = webdriver.ChromeOptions() chrome_options.binary_location = str(os.getenv('GOOGLE_CHROME_BIN')) chrome_options.add_argument("--headless") chrome_options.add_argument("--start-maximized") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-extensions") chrome_options.add_argument('--disable-dev-shm-usage') chrome_options.add_argument("--disable-gpu") chrome_options.add_argument('--disable-software-rasterizer') chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166") chrome_options.add_argument("--disable-notifications") chrome_options.add_argument('--window-size=1920,1080') chrome_options.add_experimental_option("prefs", { "download.default_directory": f"{settings.MEDIA_ROOT}\\AppVimeoApp\\videos", "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing_for_trusted_sources_enabled": False, "safebrowsing.enabled": False } ) driver = webdriver.Chrome(executable_path=str(os.getenv('CHROMEDRIVER_PATH')), chrome_options=chrome_options) driver.get('videolink') time.sleep(5) while True: try: driver.find_element(by=By.XPATH, value='/html/body/div[2]/div[1]/div[6]/div[2]/div[1]/a').click() break except: time.sleep(1) continue time.sleep(5) return ("Downloaded") I am very grateful if you can help me. Thank you. -
django signals - reverse lookup
I have 2 models Product and ProductComponent. What I am trying to do is to copy the user's id from Product model to all components that are related to this product in ProductComponent model. Let's say that we have a user with id=1. We also have a product with id=3 that contains 3 components. Right now when a user adds a product to the cart it adds the user only to the Product model. What I want is to add user to ProductComponent automatically so if user adds a product to the cart then it will add the user's id to all components that are related to this product in the ProductComponent model. In SQL what should happen when user adds product to cart is something like this: product_id user_id 3 1 productcomponent_id user_id 1 1 2 1 3 1 For now, I need to manually add each component even if I added product to cart. I want to automate it so adding product to cart will be also adding users's id to all components related to this product. I tried to use post_save and m2m_changed but I am not sure how to copy user's id from Product model to … -
django.db.utils.NotSupportedError: Oracle 19 or later is required (found 12.2.0.1.0)
'''note: I installed oracle instance for windows ''' with connections['trdb'].cursor() as cursor: cursor.execute(sql) row = cursor.fetchall() col = cursor.description cursor.close -
problem with service worker accessing django admin when serving react as main url
Im encountering an odd problem. I serve react as main url("/") of my django backend. When Im trying to access django admin in "/admin/" it will interrupt by service worker and it is trying to route with react-router-dom instead of routing with django urls. When i unregister service worker or hard refresh it fixes my problem. Im really confused. thanks for your help in advance. my django main urls: urlpatterns = [ path('admin/', admin.site.urls), ... path('', TemplateView.as_view(template_name='index.html')), path("<str:public_url>", views.public, name="public") ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns.append(path('<path:route>', TemplateView.as_view(template_name='index.html'))) Im using BrowserRouter and default Service Worker of create-react-app. -
how to sort object in django
def bubble_sort(nts): nts_len = len(nts) for i in range(nts_len): for p in range(nts_len - i - 1): if nts[p] < nts[p+1]: t = nts[p] nts[p]= nts[p+1] nts[p+1] = t return nts def menu(request): products = Product.objects.all() if request.method == "POST": s = request.POST['select'] if s == 'Price: Low to High': element = [] for var in products: element.append(var) list_items = list(element) bb = bubble_sort(list_items) el = list(bb) print(el) pro = Product.objects.filter(id__in=bb) print(pro) products = bb # print(products) How to retrieve data from database in bubble sort for objects?TypeError: '<' not supported between instances of 'Product' and 'Product' -
pipenv modules not seen by Django manage.py
I just started working on a Django project. For virtual environment I am trying to use pipenv. Inside my working directory; First I created a virtualenv with $ pipenv install django $ pipenv install autoslug then activated it with $ pipenv shell After that, I started a Django project with $ django-admin startproject x Then I started an app within the project with $ django-admin startapp y Inside app y, I imported module "autoslug". I installed autoslug with $pipenv install django-autoslug When I try to make migrations with $ python manage.py makemigrations It gives an error no module named autoslug My virtualenv is activated and the module is installed inside it. Any help would be appreciated. Thanks! -
Django serializer read and write multiple model field with
How to read and write multiple models in Django rest framework Model Serializer. like I have created a user-create model view set API, for that, I create a Model Serializer. there I need to give multiple permissions. for that, I pass the user_permissions field with an array of permission's id. now, how can I define a field in the user Model Serializer that can create a user with this permission and then get the user with permission's data? class UserSerializer(serializers.ModelSerializer): class Meta: model = AbstractUser fields = "__all__" extra_kwargs = {'password': {'write_only': True},} extra_fields = ['user_permissions'] #view class RegistrationView(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = AbstractUser.objects.all() parser_classes = (FormParser, MultiPartParser) permission_classes_by_action = [IsAdminUser, ] def create(self, request, *args, **kwargs): response_data = super(RegistrationView, self).create(request,*args,**kwargs) return Response({"data": response_data.data}) request body { "username": "testuser", "email": "testuser@example.com", "first_name": "test", "last_name": "test", "password": "Abcd@123456", "user_permissions": [1, 2, 3, 4, 5] } required response { "id": 1, "email": "testuser@example.com", "username": "testuser", "first_name": "test", "last_name": "test", "is_superuser": false, "is_staff": false, "is_active": true, "date_joined": "2022-08-17T10:25:48.446821Z", "user_permissions": [ { "id": 1, "name": "Can add User", "codename": "add_user", "content_type": "account" }, { "id": 2, "name": "Can change User", "codename": "change_user", "content_type": "account" }, { "id": 3, "name": "Can delete User", "codename": … -
Django Template Language collapsed output
My template includes for loop and for each of iteration it decides does it create new messages container, just appends messages or closes container. room.html {% block body %} <div class="wrapper column"> <div class="content-container column"> <div class="leave row"> <div class="leave__container"> <a class="button-input button-pulse leave__button-pulse" href="{% url 'chat:index' %}">Leave</a> </div> {% if admin %} <div class="leave__container"> <input type="hidden" id="deleteUrl" data-url="{% url 'chat:delete_room' room_name %}"> <a class="button-input button-pulse leave__button-pulse leave__button-pulse_delete pointer">Delete</a> </div> {% endif %} </div> <div id="chat-log" class="chat column"> {% for chat in chats.all %} {% comment %} If user sent a message {% endcomment %} {% if chat.user_id == request.user.id %} {% comment %} If message first open container and messages {% endcomment %} {% if chat.user_id != chat.get_previous_user.id %} <div class="chat__container sender column"> <div class="chat__author">{{chat.user.username}}</div> <div class="chat__messages"> {% endif %} {% comment %} Message itself {% endcomment %} <div class="chat__message">{{chat.content}}</div> {% comment %} If message last then close messages and container {% endcomment %} {% if chat.user_id != chat.get_next_user.id %} </div> <div class="chat__posted">{{chat.timestamp}}</div> </div> {% endif %} {% comment %} If somebody else sent a message {% endcomment %} {% else %} {% comment %} If message first open container and messages {% endcomment %} {% if chat.user_id != … -
Why my product photo is not updating? But product title is updating
I have an update form to update information. Here problem is, product_title is updating but product_image is not working. Where is the problem that's for why the photo is not updating? views.py: def update_product(request,id): product = Products.objects.get(pk=id) form = update_product_info(request.POST or None, instance=product) if request.method == 'POST' and form.is_valid(): form.save() print(form.errors) messages.success(request,"Successfully product information updated.") return redirect("my_products") context = { 'product':product, "form":form } return render(request, "update_product.html", context) update form: class update_product_info(forms.ModelForm): class Meta: model = Products fields = ('product_title','product_image') widgets = { 'product_title':forms.TextInput(attrs={'class':'form-control', 'style':'font-size:13px;'}), 'product_image':forms.FileInput(attrs={'class':'form-control', 'style':'font-size:13px;'}) } template: <form action="" method="POST" class="needs-validation" style="font-size: 13px;" novalidate="" autocomplete="off" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <div class="d-flex align-items-center"> <button type="submit" class="btn btn-outline-dark ms-auto" value="Update" style="font-size: 13px;">Add</button> </div> -
can not send multiple select values to django view
I have a select and has multiple values but in backend knowledge_keywords list is empty knowledge_keywords = request.POST.getlist('knowledge_keywords') <div class="container"> <div class="input-group"> <span class="input-group-addon"> <input type="checkbox" class="form-check-input" name="key_words_check_box" value="1"> </span> <select class="hidden" id="keywords" name="knowledge_keywords" multiple="multiple" data-role="tagsinput"> </select> </div> </div> -
How can I build an authentication system with react,redux and django without using django default authentication?
I am building a web app in which I have a model in my Django which stores username, email, encrypted_password fields. Now I have asked to build an authentication system using this model with react. I can't use Django default user model. so, I am asking to you guys, can I do that in react with redux? I just want to get the Django API with password and email fields. Can I do my rest of the thing in react? if this is possible how can I do that? In short, I need to build an authentication system without using Django default users model or authentication system with react, redux? -
How to make a POST request in the ManyToManyField?
I have a UserAccess model which contains two user and articles fields. The articles field is ManyToManyField in relation to the Article model, so each user has the same list of articles associated with it. I want to change the is_blocked field using a POST request so that each article for each user is blocked individually. How to do it ? models.py class UserAccess(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, ) articles = models.ManyToManyField('Article') def __str__(self): return str(self.user) class Meta: verbose_name = "access" verbose_name_plural = 'access' class Article(models.Model): title = models.CharField(max_length=256) label = models.ImageField( upload_to='uploads/labels', blank=True, ) is_blocked = models.BooleanField(default=True) def __str__(self): if self.is_blocked == True: return f"‚{str(self.pk)}: {str(self.title)}" return f"{str(self.pk)}: {str(self.title)}" class Meta: ordering = ('pk',) verbose_name = "Article" verbose_name_plural = "Article" serializers.py class ArcticleSerializer(ModelSerializer): class Meta: model = Article fields = [ "pk", "title", "label", "is_blocked", ] class CurrentUserSerializer(ModelSerializer): class Meta: model = User fields = ["username"] class UserAccessSerializer(ModelSerializer): articles = ArcticleSerializer(many=True) user = CurrentUserSerializer(read_only=True) class Meta: model = UserAccess fields =[ "user", "articles", ] read_only_fields = ('created','updated') views.py class UserAccessViewSet(ModelViewSet): serializer_class =UserAccessSerializer pagination_class = StandardResultsSetPagination def get_queryset(self): user = self.request.user return UserAccess.objects.filter(user=user) -
How can I install argon2 from terminal?
I'm having a problem with the use of Argon2PasswordHasher class from django.contrib.auth.hashers. I'm trying to study its function, starting from encode in a very basic use. When I try to install argon2 from the terminal with: pip install argon2 it shows me a lot of error: Collecting argon2 Using cached argon2-0.1.10.tar.gz (28 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: argon2 Building wheel for argon2 (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [39 lines of output] Warning: 'classifiers' should be a list, got type 'tuple' running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.10 copying argon2.py -> build\lib.win-amd64-3.10 package init file 'phc-winner-argon2_init_.py' not found (or not a regular file) running build_ext building '_argon2' extension creating build\temp.win-amd64-3.10 creating build\temp.win-amd64-3.10\Release creating build\temp.win-amd64-3.10\Release\phc-winner-argon2 creating build\temp.win-amd64-3.10\Release\phc-winner-argon2\src creating build\temp.win-amd64-3.10\Release\phc-winner-argon2\src\blake2 creating build\temp.win-amd64-3.10\Release\src D:\VisualStudio\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DHAVE_CONFIG_H -Dinline=__inline -I./phc-winner-argon2 -I./phc-winner-argon2/src -I./phc-winner-argon2/src/blake2 -Ic:\OpenSSL-Win32\include -Iargon2-windows-stubs/include -IC:\Users\nicog\newApi\venv\include -IC:\Users\nicog\AppData\Local\Programs\Python\Python310\include -IC:\Users\nicog\AppData\Local\Programs\Python\Python310\Include -ID:\VisualStudio\VC\Tools\MSVC\14.29.30133\include -IC:\Program Files (x86)\Windows Kits\10\include\10.0.20348.0\ucrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.20348.0\shared -IC:\Program Files (x86)\Windows Kits\10\include\10.0.20348.0\um -IC:\Program Files (x86)\Windows Kits\10\include\10.0.20348.0\winrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.20348.0\cppwinrt /Tc./phc-winner-argon2/src/argon2.c /Fobuild\temp.win-amd64-3.10\Release./phc-winner-argon2/src/argon2.obj argon2.c D:\VisualStudio\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DHAVE_CONFIG_H -Dinline=__inline -I./phc-winner-argon2 -I./phc-winner-argon2/src -I./phc-winner-argon2/src/blake2 -Ic:\OpenSSL-Win32\include -Iargon2-windows-stubs/include -IC:\Users\nicog\newApi\venv\include -IC:\Users\nicog\AppData\Local\Programs\Python\Python310\include … -
How to format a number to a decimal in django template?
Hi I am trying to format a number (1999) in Django template to a decimal with 2DP, e.g. (19.99) <div class="card-body"> <p class="card-text">{{ object.max_price|stringformat:".2f" )} {{object.currency.id}}</p> <p class="card-text">{{object.min_price}} {{object.currency.id}}</p> <p class="card-text">-{{object.discount_percentage}}%</p> <p class="card-text">{{object.recommended_retail_price}} {{object.currency.id}}</p> </div> I get this error: TemplateSyntaxError at /products Could not parse the remainder: ' )} {{object.currency.id' from 'object.max_price|stringformat:".2f" )} {{object.currency.id' Request Method: GET Request URL: http://localhost:8000/products?page=1 Django Version: 4.0 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: ' )} {{object.currency.id' from 'object.max_price|stringformat:".2f" )} {{object.currency.id' I have also tried using floatformat and get a similar error: TemplateSyntaxError at /products Could not parse the remainder: ' )} {{object.currency.id' from 'object.max_price|floatformat )} {{object.currency.id' Request Method: GET Request URL: http://localhost:8000/products?page=1 Django Version: 4.0 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: ' )} {{object.currency.id' from 'object.max_price|floatformat )} {{object.currency.id' How is it possible to format an integer in Django jinja template as a decimal to 2DP? -
iam trying to create an API in python for hospital management system by using Flask
import time import pickle import os class Hospital: def init(self): self.sno=0 self.name='' self.age=0 self.sex="" self.email='' self.fname="" self.address="" self.city='' self.state='' self.height=0 self.weight=0 self.med='' self.bill=0 self.paymentmethod='' self.pno=0 self.bgroup='' self.dname='' def Input(self): self.sno=input("Enter Serial Number:") self.name=str(input("Enter Patient's Name:")) self.age=input("ENter Patient's age:") self.sex=str(input("Enter Patient's Sex(Male/Female): ")) self.fname=str(input("ENter Father's name:")) self.address=str(input("Enter Patient's Address:")) self.city=str(input("Enter Patient's City:")) self.state=input("Enter Patient's State:") self.height=input("Enter Patient's Height:") self.weight=input("Enter Patient's Weight:") self.bgroup=str(input("Enter Blood Group:")) self.dname=str("Enter Patient's Disease:") self.med=str(input("Enter Prescribed Medicine:")) self.email=str(input("ENter Patient's E-Mail:")) self.pno=input("Enter phone number:") self.bill=input("Enter Bill Amount:Rs.") self.paymentmethod=("Enter Payment Method(cash/cheque/card):") def Output(self): print ("Serial Number:-",self.sno) print("Patient's Name:-",self.name) print("Patient's age:-",self.age) print("Patient's Sex(Male/Female):-",self.sex) print("Father's name:-",self.fname) print("Patient's Address:-",self.address) print("Patient's City:-",self.city) print("Patient's State:-",self.state) print("Patient's Height:-",self.height) print("Patient's Weight:-",self.weight) print("Blood Group:-",self.bgroup) print("Patient's DIsease:-",self.dname) print("Prescribed Medicine:-",self.med) print("Patient's E-mail:-",self.email) print("Phone Number:-",self.pno) print("Bill Amount:-",self.bill) print("Payment Method:-",self.paymentmethod) ##functioning## import time import pickle import os def WriteHospital(): fout=open("Hospital1.DAT","ab") ob=Hospital() print("Enter Details::") ob.Input() pickle.dump(ob,fout) print("Record SAved") fout.close() def ReadHospital(): fin=open("Hospital1.DAT","rb") ob=Hospital() print("Hospital Details are::") while True: ob.Output() print except EOFErrortry: : fin.close def SearchHospitalSno(n): fin=open("Hospital1.DAT","rb") ob=Hospital() flag=False try: print print("/n Hospital Details Are:--") while True: ob=pickle.load(fin) if ob.Sno==n: ob.Output() flag=True break except EOFError: if not flag: print("/n") print("/n") print ("") print("") print("") fin.close def SearchHospitalEmail(n): fin=open("Hospital1.DAT","rb") ob=Hospital() -
Django - add to favourites button in ListView
I want to create add to favourites feature in ListView but I am struggling with passing product slug in each item. I have a table with the product name and Action (Add/Remove buttons). I want to allow users to add a specific product to favourites or remove it from there. models.py class Product(models.Model): [...] favourite = models.ManyToManyField(User, default=None, blank=True, related_name='favourite_product') slug = models.SlugField(unique=True, blank=True, max_length=254) views.py @login_required def products_in_favourites(request, slug): product = get_object_or_404(Product, slug=slug) added_to_favourite = False if product.favourite.filter(id=request.user.id).exists(): product.favourite.remove(request.user) added_to_favourite = False else: product.favourite.add(request.user) added_to_favourite = True context = { 'object': product, 'added_to_favourite': added_to_favourite, } if request.is_ajax(): html = render_to_string('favourite.html', context, request=request) return JsonResponse({'form': html}) class AddToFavourite(LoginRequiredMixin, ListView): template_name = "AddToFavourite.html" model = Product queryset = Product.objects.all() context_object_name = 'product_list' def get_context_data(self, **kwargs): context = super(AddToFavourite, self).get_context_data(**kwargs) product_item = get_object_or_404(Product, slug=self.kwargs['slug']) # how to pass slug of each product item here? added_to_favourite = False if product_item.cart.filter(id=self.request.user.id).exists(): added_to_favourite = True context['added_to_favourite'] = added_to_favourite AddToFavourite.html {% block body %} <section class="container"> <table class="table table-hover"> <thead> <tr> <th scope="col">Product</th> <th scope="col">Action</th> </tr> </thead> <tbody id="favourite"> {% for product in product_list %} <tr> <td>{{product.title}}</td> <td> {% include 'favourite.html' %} </td> </tr> {% endfor %} </tbody> </table> </section> {% endblock body %} {% block … -
Temporary Directory on Heroku with Django
On my django project I create a temporary directory, execute my code I need and every thing works great. When deploying on Heroku it just does not work anymore. I need to have a tempdirectory to run my process. After that my pdflatex file is saved in the database (works). It seems to be that a tmpdir is created, otherwise Heroku would not know the name of the directory. But maybe the directory is gone even before my process is over. What confuses me is that the structure of the path in local host looks quite different then in Heroku. I understand that each and every tempdir will have another name. But why is the structure with the directories different? Is it even possible to create temporary directory and work with them on Heroku? with tempfile.TemporaryDirectory() as tmpdir: print(tmpdir) process = subprocess.Popen( ['pdflatex', '-output-directory', f'{tmpdir}'], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) Print output in local host: /var/folders/b3/s6r951md2ps4332j54mkxknr0000gn/T/tmp0bqryfu_ Error output on Heroku server: this is the error message: [Errno 2] No such file or directory: '/tmp/tmpa65lghdx/texput.pdf' -
Issue installing uWSGI==2.0.19.1 on Mac M1 Monterey v12.5
Im having this error message that I dont know what to do ERROR: Command errored out with exit status 1: command: /Users/eingel.figueroa/Documents/Gitlab/practice/practice/test/bin/python3.10 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/kx/kbq3933x2tdgrwmw3wrcgvlc0000gq/T/pip-install-d3gcx0no/uwsgi_09432bb0c9b44a06af129191ab4686bd/setup.py'"'"'; file='"'"'/private/var/folders/kx/kbq3933x2tdgrwmw3wrcgvlc0000gq/T/pip-install-d3gcx0no/uwsgi_09432bb0c9b44a06af129191ab4686bd/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/kx/kbq3933x2tdgrwmw3wrcgvlc0000gq/T/pip-record-_2yqb6j2/install-record.txt --single-version-externally-managed --compile --install-headers /Users/eingel.figueroa/Documents/Gitlab/practice/practice/test/include/site/python3.10/uWSGI cwd: /private/var/folders/kx/kbq3933x2tdgrwmw3wrcgvlc0000gq/T/pip-install-d3gcx0no/uwsgi_09432bb0c9b44a06af129191ab4686bd/ Complete output (218 lines): /Users/eingel.figueroa/Documents/Gitlab/practice/practice/test/lib/python3.10/site-packages/setuptools/_distutils/dist.py:262: UserWarning: Unknown distribution option: 'descriptions' warnings.warn(msg) running install /Users/eingel.figueroa/Documents/Gitlab/practice/practice/test/lib/python3.10/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools. warnings.warn( using profile: buildconf/default.ini detected include path: ['/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include', '/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include', '/Library/Developer/CommandLineTools/usr/include', '/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks'] Patching "bin_name" to properly install_scripts dir detected CPU cores: 8 configured CFLAGS: -O2 -I. -Wall -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -DUWSGI_HAS_IFADDRS -DUWSGI_ZLIB -mmacosx-version-min=10.5 -DUWSGI_LOCK_USE_OSX_SPINLOCK -DUWSGI_EVENT_USE_KQUEUE -DUWSGI_EVENT_TIMER_USE_KQUEUE -DUWSGI_EVENT_FILEMONITOR_USE_KQUEUE -I/opt/homebrew/Cellar/pcre/8.45/include -DUWSGI_PCRE -DUWSGI_ROUTING -DUWSGI_UUID -DUWSGI_VERSION=""2.0.19.1"" -DUWSGI_VERSION_BASE="2" -DUWSGI_VERSION_MAJOR="0" -DUWSGI_VERSION_MINOR="19" -DUWSGI_VERSION_REVISION="1" -DUWSGI_VERSION_CUSTOM="""" -DUWSGI_YAML -I/opt/homebrew/Cellar/yajl/2.1.0/include/ -DUWSGI_JSON -DUWSGI_JSON_YAJL -DUWSGI_XML -DUWSGI_XML_EXPAT -DUWSGI_PLUGIN_DIR=""."" -DUWSGI_DECLARE_EMBEDDED_PLUGINS="UDEP(python);UDEP(gevent);UDEP(ping);UDEP(cache);UDEP(nagios);UDEP(rrdtool);UDEP(carbon);UDEP(rpc);UDEP(corerouter);UDEP(fastrouter);UDEP(http);UDEP(signal);UDEP(syslog);UDEP(rsyslog);UDEP(logsocket);UDEP(router_uwsgi);UDEP(router_redirect);UDEP(router_basicauth);UDEP(zergpool);UDEP(redislog);UDEP(mongodblog);UDEP(router_rewrite);UDEP(router_http);UDEP(logfile);UDEP(router_cache);UDEP(rawrouter);UDEP(router_static);UDEP(sslrouter);UDEP(spooler);UDEP(cheaper_busyness);UDEP(symcall);UDEP(transformation_tofile);UDEP(transformation_gzip);UDEP(transformation_chunked);UDEP(transformation_offload);UDEP(router_memcached);UDEP(router_redis);UDEP(router_hash);UDEP(router_expires);UDEP(router_metrics);UDEP(transformation_template);UDEP(stats_pusher_socket);" -DUWSGI_LOAD_EMBEDDED_PLUGINS="ULEP(python);ULEP(gevent);ULEP(ping);ULEP(cache);ULEP(nagios);ULEP(rrdtool);ULEP(carbon);ULEP(rpc);ULEP(corerouter);ULEP(fastrouter);ULEP(http);ULEP(signal);ULEP(syslog);ULEP(rsyslog);ULEP(logsocket);ULEP(router_uwsgi);ULEP(router_redirect);ULEP(router_basicauth);ULEP(zergpool);ULEP(redislog);ULEP(mongodblog);ULEP(router_rewrite);ULEP(router_http);ULEP(logfile);ULEP(router_cache);ULEP(rawrouter);ULEP(router_static);ULEP(sslrouter);ULEP(spooler);ULEP(cheaper_busyness);ULEP(symcall);ULEP(transformation_tofile);ULEP(transformation_gzip);ULEP(transformation_chunked);ULEP(transformation_offload);ULEP(router_memcached);ULEP(router_redis);ULEP(router_hash);ULEP(router_expires);ULEP(router_metrics);ULEP(transformation_template);ULEP(stats_pusher_socket);" *** uWSGI compiling server core *** [thread 1][gcc] core/utils.o [thread 2][gcc] core/protocol.o [thread 4][gcc] core/socket.o [thread 3][gcc] core/logging.o [thread 6][gcc] core/master.o [thread 7][gcc] core/master_utils.o [thread 5][gcc] core/emperor.o [thread 0][gcc] core/notify.o core/utils.c:3676:6: warning: variable 'pos' set but not used [-Wunused-but-set-variable] int pos = 0; ^ 1 warning generated. [thread 1][gcc] core/mule.o [thread 2][gcc] core/subscription.o [thread 4][gcc] core/stats.o …