Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to ORM filter a query with parameter list exactly?
I have a query filter query_1 = Model.objects.filter(param = param) I need to filter this list to another ORM and return true or flase only if all the data in the query_1 is in the second query. Like, query_2 = AnotherModel.objects.filter(field__in=query_1) return True only if all the objects in the query_1 list is in the query_2. -
Non ORM Backend in Django
I'm working with a database that I can't alter, it doesn't have PK or FK which makes it difficult to interact with it using ORM Backend in Django. So I want to know if non ORM Backend in Django offers the same flexibility? Here is an example using ORM backend : <div class="table-responsive"> <table id="table_devis" class="table table-hover "> <thead class="table-dark"> <tr> <th scope="col">Referance</th> <th scope="col">Date de creation</th> <th scope="col">Date d'expiration</th> <th scope="col">Client</th> <th scope="col">Total</th> <th scope="col">Commercial</th> </tr> </thead> <tbody> {% for dev in devis %} <tr> <th scope="row"><a href="{% url 'view_devis' dev.pk %}">DV{{dev.id }}</a></th> <td>{{ dev.date_ecriture }}</td> <td>{{ dev.date_expiration }}</td> <td>{{dev.client.nom}}</td> <td>{{ dev.total}} DH</td> <td>{{ dev.commercial.first_name}}</td> </tr> {% endfor %} </tbody> </table> </div> Can I do something similar using non ORM backend in Django??? -
Django(TypeError: expected string or bytes-like object)
As I am using django and mongodb, I need to submit the values with html form created and store it in the database, But this error occurs when I submit the value in the form.I will share you my code. My template template/insert.html and Jquery file, <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Adding New Value</title> <link rel="stylesheet" href="./form-to-json.css" type="text/css"> </head> <body> <h1>Adding New Member form:</h1> <!-- <form method="POST"> --> <form action="new" method="POST" id="formsave"> {% csrf_token %} <div class="mb-3"> <label>Id</label> <input type="text" id="id" class="form-control"/> </div> <div class="mb-3"> <label>applied_on</label> <input type="text" id="applied_on" class="form-control"/> </div> <div class="mb-3"> <label>city</label> <input type="text" id="city" class="form-control"/> </div> <div class="mb-3"> <label>country</label> <input type="text" id="country" class="form-control"/> </div> <div class="mb-3"> <label>courseId</label> <input type="text" id="courseId" class="form-control"/> </div> <div class="mb-3"> <label>courseName</label> <input type="text" id="courseName" class="form-control"/> </div> <div class="mb-3"> <label>created</label> <input type="text" id="created" class="form-control"/> </div> <div class="mb-3"> <label>dob</label> <input type="text" id="dob" class="form-control"/> </div> <div class="mb-3"> <label>eligibility_verified</label> <input type="text" id="eligibility_verified" class="form-control"/> </div> <div class="mb-3"> <label>email_id</label> <input type="email" id="email_id" class="form-control"/> </div> <div class="mb-3"> <label>exactdup</label> <input type="text" id="exactdup" class="form-control"/> </div> <div class="mb-3"> <label>exam_registration</label> <input type="text" id="exam_registration" class="form-control"/> </div> <div class="mb-3"> <label>ilearnUserID</label> <input type="text" id="ilearnUserID" class="form-control"/> </div> <div class="mb-3"> <label>last_action_by</label> <input type="text" id="last_action_by" class="form-control"/> </div> <div class="mb-3"> <label>localChapterId</label> <input type="text" id="localChapterId" class="form-control"/> </div> <div class="mb-3"> … -
Any Idea on optimizing Custom Columns in django models
There are 100s of Custom Columns in Database While mapping in Models it is complicated. I need solution how we can reduce the below code. Here is the code written in models.py in Django for time being. class LS_Additional_Values(models.Model): LSCode = models.CharField(db_column='LSCode',primary_key=True,max_length=8) LSFirmCode = models.DecimalField(db_column='LSFirmCode', max_digits=4, decimal_places=0) Table = models.CharField(db_column='Table', max_length=100) pkey = models.CharField(db_column='pKey', max_length=50,null=False) Custom1 = models.CharField(db_column='Custom1', max_length=500,null=True) Custom2 = models.CharField(db_column='Custom2', max_length=500,null=True) Custom3 = models.CharField(db_column='Custom3', max_length=500,null=True) Custom4 = models.CharField(db_column='Custom4', max_length=500,null=True) Custom5 = models.CharField(db_column='Custom5', max_length=500,null=True) Custom6 = models.CharField(db_column='Custom6', max_length=500,null=True) Custom7 = models.CharField(db_column='Custom7', max_length=500,null=True) Custom8 = models.CharField(db_column='Custom8', max_length=500,null=True) Custom9 = models.CharField(db_column='Custom9', max_length=500,null=True) Custom10 = models.CharField(db_column='Custom10', max_length=500,null=True) Custom11 = models.CharField(db_column='Custom11', max_length=500,null=True) Custom12 = models.CharField(db_column='Custom12', max_length=500,null=True) Custom13 = models.CharField(db_column='Custom13', max_length=500,null=True) Custom14 = models.CharField(db_column='Custom14', max_length=500,null=True) Custom15 = models.CharField(db_column='Custom15', max_length=500,null=True) ....... Custom97 = models.CharField(db_column='Custom97', max_length=500,null=True) Custom98 = models.CharField(db_column='Custom98', max_length=500,null=True) Custom99 = models.CharField(db_column='Custom99', max_length=500,null=True) Custom100 = models.CharField(db_column='Custom100', max_length=500,null=True) Created_by = models.CharField(db_column='Created By', max_length=100) Date_Of_Item_Created = models.DateField(db_column='Date Of Item Created') Modified_by = models.CharField(db_column='Modified By',max_length=100) Date_of_Modification = models.DateTimeField(db_column='Date of Modification') -
React - Cannot read properties of undefined (reading 'params')
A similar question about the same tutorial was asked already here. Sadly this is a more advanced part of the tutorial and I don't seem to get this. Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'params') at fetchProduct (ProductScreen.js:16:1) at ProductScreen.js:19:1 at commitHookEffectListMount (react-dom.development.js:23150:1) at commitPassiveMountOnFiber (react-dom.development.js:24926:1) at commitPassiveMountEffects_complete (react-dom.development.js:24891:1) at commitPassiveMountEffects_begin (react-dom.development.js:24878:1) at commitPassiveMountEffects (react-dom.development.js:24866:1) at flushPassiveEffectsImpl (react-dom.development.js:27039:1) at flushPassiveEffects (react-dom.development.js:26984:1) at performSyncWorkOnRoot (react-dom.development.js:26076:1) My ProductScreen.js: function ProductScreen({ match }) { const [product, setProduct] = useState([]) useEffect(() =>{ async function fetchProduct() { const { data } = await axios.get(`/api/products/${match.params.id}`) setProduct(data) } fetchProduct() },[]) My App.js: function App() { return ( <Router> <Header /> <main className="py-5"> <Container> <Routes> <Route path='/' element={<HomeScreen />} exact/> <Route path='/product/:id' element={<ProductScreen />} /> </Routes> </Container> </main> <Footer/> </Router> ); } export default App; Thank for the help! -
Get files content type of stored file using file system storage Django
I want to get the content type of the file that is stored in the media folder using FileSystemStorage Django. I am saving files in the media folder. While fetching files from the media folder I want to fetch the content type of the file along with the name. -
Django's .annotate generates an SQL operation per instance in queryset
I have a problem where my annotation for lowest related gross_price seems to be causing n+1 amount of queries. I have two models Product and ProductOption, which looks like: class Product(models.Model): ... class ProductOption(models.Model): product = models.ForeignKey(Product, related_name="options", ...) gross_price = models.DecimalField(...) In my manager queryset method, which lists all products i have the following code: def annotate_lowest_price(self) -> QuerySet["models.Product"]: return self.prefetch_related("options").annotate(lowest_price=Min("options__gross_price") And it's used in the code like this: def get_products_list(): products = Product.objects.filter(...).annotate_lowest_price() ... The method outputs as expected, but doing a .explain() shows that it generates a SELECT MIN operation per instance in the queryset. E.g if you have 10 products, it will do 10 queries: SELECT "products_product"."id", ... SELECT "products_productoption"."id", ... SELECT MIN("products_productoption"."gross_price") AS "gross_price__min" FROM "products_productoption" WHERE ("products_productoption"."product_id" = 666 AND "products_productoption"."status" = 3) SELECT MIN("products_productoption"."gross_price") AS "gross_price__min" FROM "products_productoption" WHERE ("products_productoption"."product_id" = 668 AND "products_productoption"."status" = 3) SELECT MIN("products_productoption"."gross_price") AS "gross_price__min" FROM "products_productoption" WHERE ("products_productoption"."product_id" = 681 AND "products_productoption"."status" = 3) SELECT MIN("products_productoption"."gross_price") AS "gross_price__min" FROM "products_productoption" WHERE ("products_productoption"."product_id" = 672 AND "products_productoption"."status" = 3) SELECT MIN("products_productoption"."gross_price") AS "gross_price__min" FROM "products_productoption" WHERE ("products_productoption"."product_id" = 685 AND "products_productoption"."status" = 3) SELECT MIN("products_productoption"."gross_price") AS "gross_price__min" FROM "products_productoption" WHERE ("products_productoption"."product_id" = 671 AND "products_productoption"."status" = 3) SELECT … -
ImportError: cannot import name 'djongo_access_url' from 'djongo'
I am getting the following error using Djongo with Mongodb in a django server: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1009, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "/home/cchilders/.local/lib/python3.10/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/cchilders/.local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/cchilders/.local/lib/python3.10/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/cchilders/.local/lib/python3.10/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/cchilders/.local/lib/python3.10/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/cchilders/.local/lib/python3.10/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/cchilders/.local/lib/python3.10/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/home/cchilders/.local/lib/python3.10/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/cchilders/.local/lib/python3.10/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/cchilders/.local/lib/python3.10/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/cchilders/.local/lib/python3.10/site-packages/django/urls/resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed … -
Django not migrating after makemigrations
I'm working on a Django project with some apps, but from the beginning, I had problems with 'makemigrations' and 'migrate'. These two are giving me some non-sens errors that I can't find solutions to. And from yesterday when I copied someones else code and replaced it with mine, 'makemigrations' works but 'migrate' doesn't. Here are my models.py: from django.db import models from django.utils.translation import gettext_lazy as _ # third party apps from mptt.models import MPTTModel, TreeForeignKey from ckeditor.fields import RichTextField # Local apps from account.models import User from extentions.utils import jalali_converter class Category(MPTTModel): title = models.CharField(max_length=100, verbose_name=_('عنوان')) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name="children", verbose_name=_('فرزند')) is_child = models.BooleanField(default=False, verbose_name=_('فرزند است؟')) slug = models.SlugField(unique=True, null=True, blank=True, allow_unicode=True) created = models.DateTimeField(auto_now_add=True, verbose_name=_('زمان ساخت')) updated = models.DateTimeField(auto_now=True, verbose_name=_('زمان بروزرسانی')) class Meta: verbose_name = _('دسته بندی') verbose_name_plural = _('دسته بندی ها') def __str__(self): return self.title class Video(models.Model): creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='videos', verbose_name=_('بارگذار')) title = models.CharField(max_length=100, unique=True, verbose_name=_('عنوان ویدئو')) slug = models.SlugField(unique=True, null=True, blank=True, allow_unicode=True) category = models.ManyToManyField(Category, related_name='cvideos', verbose_name=_('دسته بندی ها')) about_video = RichTextField(verbose_name=_('درباره ویدئو')) views = models.PositiveBigIntegerField(default=1, verbose_name=_('بازدید')) video = models.FileField(upload_to='videos/video_files', verbose_name=_('ویدئو')) image = models.ImageField(upload_to='videos/pictures/', verbose_name=_('عکس نمایشی')) time = models.IntegerField(default=1, verbose_name=_('مدت زمان ویدئو')) created = models.DateTimeField(auto_now_add=True, verbose_name=_('تاریخ ساخت')) updated = models.DateTimeField(auto_now=True, verbose_name=_('تاریخ … -
Should I learn Django or Node js in 2022? [closed]
I know Python, so should I learn Django as a backend framework or should I learn JavaScript so that I can go with Node js as a backend framework?? Which is worth learning in 2022? -
'dict' object has no attribute 'encode' in AES django
so i want encrypt file using key i was input. but there's error message: 'dict' object has no attribute 'encode' and the line that's error like this. i already read another website, i must add encode('utf8'), but it not works on me. i was copy the code using this by tweaksp aes = AES.new(key.encode('utf8'), AES.MODE_CTR, counter=ctr.encode('utf8')) if you need full code, here's: # AES supports multiple key sizes: 16 (AES128), 24 (AES192), or 32 (AES256). key_bytes = 16 # Takes as input a 32-byte key and an arbitrary-length plaintext and returns a # pair (iv, ciphtertext). "iv" stands for initialization vector. def encrypt(key, testpass): assert len(key) == key_bytes print(testpass) print(key) # Choose a random, 16-byte IV. iv = Random.new().read(AES.block_size) # Convert the IV to a Python integer. iv_int = int(binascii.hexlify(iv), 16) # Create a new Counter object with IV = iv_int. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int) # Create AES-CTR cipher. aes = AES.new(key.encode('utf8'), AES.MODE_CTR, counter=ctr.encode('utf8')) # Encrypt and return IV and ciphertext. ciphertext = aes.encrypt(testpass) print(iv) print(ciphertext) return (iv, ciphertext) i called that function like this enkripsi = encrypt("testingtesting11", testpass) -
How to update fields on import Django?
I need to update fields on import for ManyToMany bulk editing. When importing, now I can only add products, because when I try to add already existing fields, I get a message about already existing IDs. How can I update products using import? admin.py class ProductResource(resources.ModelResource): class Meta: model = Part class PartAdmin(ImportExportActionModelAdmin): resource_class = ProductResource filter_horizontal = ('analog',) admin.site.register(Part, PartAdmin) models.py class Part(models.Model): brand = models.CharField('Производитель', max_length=100) number = models.CharField('Артикул', max_length=100, unique=True) name = models.CharField('Название', max_length=100) description = models.TextField('Комментарий', blank=True, max_length=5000) analog = models.ManyToManyField('self', blank=True, related_name='AnalogParts') images = models.FileField('Главное изображение', upload_to = 'parts/', blank=True) images0 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) images1 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) images2 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) def __str__(self): return str(self.brand + " " + self.number + " " + self.name) return self.name -
how to show a button in admin panel with a particular link format
I have an order field in my models class Order(models.Model): STATUS = ( ('Unpaid', 'Unpaid'), ('Paid', 'Paid'), ('Accepted', 'Accepted'), ('Completed', 'Completed'), ('Cancelled', 'Cancelled'), ) user = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) payment = models.ForeignKey(Payment, on_delete=models.SET_NULL, blank=True, null=True) payment_method = models.CharField(max_length=100,blank=True,null=True) order_number = models.CharField(max_length=20,blank=True, null=True) first_name = models.CharField(max_length=50,blank=True, null=True) last_name = models.CharField(max_length=50,blank=True, null=True) phone = models.CharField(max_length=15,blank=True, null=True) email = models.EmailField(max_length=50,blank=True, null=True) address_line_1 = models.CharField(max_length=50,blank=True, null=True) address_line_2 = models.CharField(max_length=50, blank=True, null=True) country = models.CharField(max_length=50,blank=True, null=True) state = models.CharField(max_length=50,blank=True, null=True) city = models.CharField(max_length=50,blank=True, null=True) order_note = models.CharField(max_length=100, blank=True, null=True) order_total = models.FloatField(blank=True, null=True) tax = models.FloatField(blank=True, null=True) status = models.CharField(max_length=10, choices=STATUS, default='New') ip = models.CharField(blank=True, null=True, max_length=20) is_ordered = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) pin_code = models.CharField(max_length=7,blank=True,null=True) bill_url = models.CharField(max_length=100,blank=True,null=True,) def full_name(self): return f'{self.first_name} {self.last_name}' def full_address(self): return f'{self.address_line_1} {self.address_line_2}' def __str__(self): return self.order_number based on the id of the url i have an endpoint /order/download-bill/{order.id} So what i want in my admin panel i want the admin have a button on which he click and the url trigger which will automatically download the bill -
How to get all entries of the item if it has one specific value
I have a Car Model something like below: id | car_name | test_type 1 | carA | P 2 | carB | Q 3 | carC | Q 4 | carA | Q I want to query it in such a way if carA has 'P' as its test_type then result must also contains all the entries for carA. Expected result for carA: id | car_name | test_type 1 | carA | P 4 | carA | Q Is there a way to do this in Django? -
The annotation x conflicts with a field on the model
I want to remove/replace some properties from list() call on Django rest framework call. e.g. I have ip_address on the db table, also adds ip_address when perform_create() called, but it should not be shown/included on list() and retrieve() calls. On retrieve calls, I can make it simply overriding the method then by adding instance.ip_address = None. But the problem now I have is on list() calls, I need to modify properties of a queryset object. I tried the following, o = ThreadedComment.objects.all() o.annotate(ip_address=Value('', output_field=CharField())).all() but I got an error: The annotation 'ip_address' conflicts with a field on the model. Is there a way to remove/override/replace an properly on queryset in Django? Thanks -
How can I fix django error? "template does not exist"
I started Django few days ago and I am stuck now. I got error like this. django.template.exceptions.TemplateDoesNotExist: home.html but I don't know how to fix it. views.py from django.shortcuts import render from django.http import HttpResponse from .models import ToDoList, Item def index(response, id): ls = ToDoList.objects.get(id=id) return render(response, "main/base.html", {"name":ls.name}) def home(response): return render(response, "main/home.html", {'name':'test'}) base.html <html> <head> <title>Website</title> </head> <body> <p>{{name}}</p> </body> </html> home.html {% extends 'main/base.html' %} Both html files are in file named templates I thought template might have something to do with it and checked it. setting.py 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', ], }, }, ] Does someone help me out? -
Celery receives tasks from rabbitmq, but not executing them
I have a Django project and have setup Celery + RabbitMQ to do heavy tasks asynchronously. When I call the task, RabbitMQ admin shows the task, Celery prints that the task is received, but the task is not executed. Here is the task's code: @app.task def dummy_task(): print("I'm Here") User.objects.create(username="User1") return "User1 Created!" In this view I send the task to celery: def task_view(request): result = dummy_task.delay() return render(request, 'display_progress.html', context={'task_id': result.task_id}) I run celery with this command: $ celery -A Snappshop worker -l info --concurrency=2 --without-gossip This is output of running Celery: -------------- celery@DESKTOP-8CHJOEG v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- Windows-10-10.0.19044-SP0 2022-08-22 10:10:04 *** --- * --- ** ---------- [config] ** ---------- .> app: proj:0x23322847880 ** ---------- .> transport: amqp://navid:**@localhost:5672// ** ---------- .> results: *** --- * --- .> concurrency: 2 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] .proj.celery.debug_task . entitymatching.tasks.create_and_learn_machine . entitymatching.tasks.dummy_task [2022-08-22 10:10:04,068: INFO/MainProcess] Connected to amqp://navid:**@127.0.0.1:5672// [2022-08-22 10:10:04,096: INFO/MainProcess] mingle: searching for neighbors [2022-08-22 10:10:04,334: INFO/SpawnPoolWorker-1] child process 6864 calling self.run() [2022-08-22 10:10:04,335: INFO/SpawnPoolWorker-2] child process 12420 calling self.run() [2022-08-22 10:10:05,134: INFO/MainProcess] mingle: all alone … -
django-allauth + django-invitations: IntegrityError at /accounts/signup/, duplicate username
I am using django-allauth + django-invitations. When I access the url in the emailed invitation sent from django-invitations, I receive this error. IntegrityError at /accounts/signup/ duplicate key value violates unique constraint "accounts_userplus_username_key" DETAIL: Key (username)=() already exists. Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 4.0.5 Exception Type: IntegrityError Exception Value: duplicate key value violates unique constraint "accounts_userplus_username_key" DETAIL: Key (username)=() already exists. UserPlus is my custom model name -
Unable to send Xml request
Am having issue sending xml request in pthon because i don't know how to render python code in xml. I have no idea how to render or navigate xml text like in example below or how to render python code in xml text before sending the python request. def start_xml_payment(request): if request.method == 'POST': form = FormPaymentForm(request.POST) if form.is_valid(): payment = form.save() first_name = request.user.first_name last_name = request.user.last_name email = request.user.email serdate = datetime.datetime.now() ref = payment.ref amount = payment.amount fees = payment.fees datejson_str = json.dumps({'created_at': serdate}, default=str) url = 'https://secure.powerpay.com/API/v6/' xml = ''' <?xml version="1.0" encoding="utf-8"?> <API3G> <code>4332-9D7F-4E09-96D4-3D44E7A83EA3</Code> <Transaction> <PaymentAmount>{amount}</PaymentAmount > <customerEmail>{email}</customerEmail> </Transaction> <Services> <Service> <ServiceDate>{datejson_str}</ServiceDate> </Service> </Services> </API3G> ''' headers = {'Content-Type': 'application/xml'} response = requests.post(url, data=xml, headers=headers) response_data = response.json() TransToken = response_data["TransToken"] cashier_response = 'https://secure.powerpay.com/p.php?ID={TransToken}' return HttpResponseRedirect (cashier_response) else: form = FormPaymentForm(request.POST) return render(request, 'dpo/start_dpo_payment.html', {'form': form}) Response <?xml version="1.0" encoding="utf-8"?><API3G><Result>000</Result><ResultExplanation>Transaction created</ResultExplanation><TransToken>803E06BC-CB80-4671-9F92-90326411ACFC</TransToken><TransRef>R39855046</TransRef></API3G> I want to navigate through this xml response and fetch TransToken TransToken = response_data["TransToken"] i want something like this cashier_response = 'https://secure.powerpay.com/p.php?ID={TransToken}' Issue 1 i have issue fetching the Transtoken because am unable to navigate through the xml response to get the transtoken and merge the transtoken to my url. I need help in … -
ImportError ugettext_lazy as _
I am using Django 4 for my webApp and I started getting this error when I want to setup Authentication. I checked all the forum and I found that they suggest to import gettext_lazy as _. But it doesn't work. Any suggestions? -
Uploading a File to database in django from Google drive
As the title suggest, I am trying to figure out how to upload from google drive to my database in PostgreSQL and have gotten nowhere. Would really appreciate some direction. -
How to display timedelta object in grouped queryset as duration field with Django REST Framework?
I have AssigneeLog model class that stores user's clock-in and clock-out on each task. from django.db import models from django.utils import timezone class AssigneeLog(models.Model): topic = models.ForeignKey(to=Topic, on_delete=models.CASCADE, blank=True) assignee = models.ForeignKey(to=User, on_delete=models.CASCADE, blank=True, help_text='Saved in case topic assignee is changed.') time_in = models.DateTimeField(default=timezone.now, blank=True, help_text='Default to current time.') time_out = models.DateTimeField(null=True, blank=True, help_text='Null at the start of time-in.') I want to list AssigneeLogs grouped by date and calculate how much time spent daily for every user-task combination. I'm able to do it, but the total_time annotated value is displayed in seconds even though I've set output_field argument to django.db.models.DurationField. When the queryset isn't grouped I can get it done with serializing the queryset using ModelSerializer class with rest_framework.serializers.DurationField. DRF view extra action method: from django.db import models from django.db.models.functions import TruncDate from rest_framework.response import Response from zoneinfo import ZoneInfo @action(methods=['post'], detail=False) def get_report(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) datetime_from = serializer.validated_data.get('datetime_from') # ex: "2022-08-01T00:00:00" datetime_to = serializer.validated_data.get('datetime_to') # ex: "2022-08-22T09:00:00" request_tz = serializer.validated_data.get('timezone') # ex: "Etc/GMT+7" logs = AssigneeLog.objects.filter( time_in__gte=datetime_from, time_out__lte=datetime_to ).annotate( date=TruncDate('time_in', tzinfo=ZoneInfo(request_tz)), # truncate to date with tz and add to select list. ).order_by('date').values('date').annotate( total_time=Sum(F('time_out')-F('time_in'), output_field=models.DurationField()) ).values('topic__id', 'topic__name', 'topic__description', 'assignee__name', 'date', 'total_time') return Response(data=logs) Output: [ { … -
How do I change the colum name of model in Django Admin?
My admin.py file from django.contrib import admin from . models import contactEnquiries class ContactAdmin(admin.ModelAdmin): list_display = ['cn_name', 'cn_email', 'cn_number'] @admin.display(description='Name') def cn_name(self, obj): return obj admin.site.register(contactEnquiries, ContactAdmin) I want to display the column titles as - Name, Email, Number instead of 'cn_name', 'cn_email', 'cn_number' . I tried the above code but I am not sure how to do it? Can anyone please help? -
How do I access objects (user info) across Django models? (Foreign Key, Beginner)
I have a Profile model and a Post model in my Django project: class Profile(models.Model): """ User profile data """ user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='profile') first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) id_user = models.IntegerField() bio = models.TextField(max_length=280, blank=True) def __str__(self): return str(self.user) class Post(models.Model): """ Model for user-created posts """ id = models.UUIDField(primary_key=True, default=uuid.uuid4) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='post') post_text = models.TextField() created_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.user I want to be able to display a user's first_name and last_name on their posts (which are shown on index.html with other all user posts), along with their username. {% for post in posts %} <div class="row d-flex justify-content-between"> <h5 class="col-12 col-md-6">{{ first_name here }} {{ last_name here }}</h5> <h5 class="col-12 col-md-6">(@{{ post.user }})</h5> </div> I can display the username just fine (post.user above) because it's in the Post model. The first_name and last_name are in the Profile model, however, and I just can't figure out a way to access them. View: @login_required(login_url='signin') def index(request): """ View to render index """ user_object = User.objects.get(username=request.user.username) user_profile = Profile.objects.get(user=user_object) posts = Post.objects.all() context = {'user_profile': user_profile, 'posts': posts, } return render(request, 'index.html', context) As well as getting all Post objects, my … -
When disconnect or refresh Django channels websocket "took too long to shut down and was killed"
I am using Django Channel for a real-time sending and saving data but when I refresh the page the error came up. log Application instance <Task pending name='Task-2' coro=<StaticFilesWrapper.__call__() running at path\channels\staticfiles.py:44> wait_for=<Future pending cb=[Task.task_wakeup()]>> for connection <WebSocketProtocol client=['127.0.0.1', 50991] path=b'/ws/graph/'> took too long to shut down and was killed. consumer.py async def connect(self): await self.accept()