Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'NoneType' object is not iterable - pyModbusTCP.client
I am making a program in django python that reads tags from a plc by modbus, the program reads a table where the ip addresses and the addresses of registers are found, it makes a loop and in each turn it inserts an address of a new register. Everything works perfectly in the first round when reading the first record, but the problem occurs when it analyzes the second record in the table with the loop, it returns 'None', which I do not understand since those records have already been individually validated and if they have as such a value, even running the same code and reading an individual tag if it works, the error occurs when I want to read several tags at the same time from a table with a loop. I use read_holding_registers to read the records and I use the library: from pyModbusTCP.client import ModbusClient This is my code: while True: try: queryset_modbus = tagopc_link_device.objects.filter(tag_type='MODBUS').values_list('id', 'tag_name', 'tag_type', 'source_ip_address', 'source_ip_port', 'register_len', 'modbus_type', 'device_id', 'digitalinput_id') if queryset_modbus: utility.logInfo('modbus', 'Reading Tags from model - modbus', "INFO") try: for row in queryset_modbus: #Parameters ... tag = row[1] modbusAddress = int(tag) - 1 longitud = row[5] # Parameters Modbus ... modbus … -
Cannot access the foreignkey data in datatables
I have provided the javascript below. Please note the one with name "teacher". This teacher is basically a foriegn key. However when I try to console.log the row, it doesnt show me that particular array value as an object or the data returned as an object and instead it returns a string since it uses def __str__ on django models. Hence im not able to get the particular value, i.e teacher.first_name or in this case data.first_name P.S. Im using django-datatables-view for providing the ajax url. $(document).ready( function () { $('.table').DataTable({ "columnDefs": [ { name: 'date_created', orderable: true, searchable: true, targets: [0], }, { name: 'name', orderable: true, searchable: true, targets: [1], }, { name: 'email', orderable: true, searchable: true, targets: [2], }, { name: 'phone', orderable: true, searchable: true, targets: [3], }, { name: 'course', orderable: true, searchable: true, targets: [4], }, { name: 'remarks', orderable: true, searchable: true, targets: [5], }, { name: 'teacher', orderable: true, searchable: true, targets: [6], render: function(data, type, row){ return data.first_name + "<br>(" + data + ")" } }, { name: 'is_enrolled', orderable: true, searchable: true, targets: [7], render: function(data, type, row){ if (data === "True"){ return "<i class='fa fa-check text-success text'></i>" } else{ … -
JOIN ILLUMINATI SECRET SOCIETY +27710571905
JOIN ILLUMINATI SECRET SOCIETY +27710571905 in South Africa, Uganda, Zambia, Zimbabwe, UK, USA, Canada, Malawi,Botswana, Swaziland, South Sudan and in cities like Sasolburg,Limpopo,Witbank,Standarton,Secunda,Middelburg,Johannesburg,Vanderbijlpark,Secunda,Soweto Cape Town,Burgersfort, Polokwane,Thohoyandou, phalaborwa, mokopane, bochum, lebowakgomo, mankweng, Seshego, dendron, Giyani, Lephalale, musina,Alexandra Johannesburg,New york,Ohio,California,New mexico,London,Manchester,Liverpool,Kampala,Kigali,Lenasia, Midrand, Randburg, Roodepoort,Sandton, Alberton ,Germiston, Benoni, Boksburg ,Rakpan Daveyton, Duduza ,Edenvale, Impumelelo, Isando Katlehong, Kempton Park, KwaThema ,Nigel Reiger,Park Springs, Tembisa, Thokoza, Tsakane, Vosloorus ,Wattville ,Atteridgaeville,Centurion,Hammanskraal, Irene, Mamelodi ,Pretoria,Soshanguve,Boipatong, Bophelong,Evaton,Sebokeng, Sharpeville,Vereeniging, Meyerton,Heidelberg,Ratanda,Bronkhorstspruit,Ekangala,Kungwini,Bronberg,Cullinan,Refilwe,Zithobeni,Carltonville,Khutsong,Kagiso,Kromdraai,Krugersdorp,Magaliesburg, Muldersdrift, Mohlaken,Randfontein,Bekkersdal,testonaria,Kimberley,Upington,Kuruman,Sprinbok,Kathu Ritchie Pietermaritzburg,Bellville,Bloemfontein. If you're ready to join the great brotherhood of illuminati secret society kingdom today the door is open for new members. Headquarters at South Africa and USA kindly inbox the Great brotherhood illuminati Prof Bob. Email address now bobspells96@gmail.com Or contact him on whats-app mobile now +27710571905 for more information. https://illuminatiwithprofbob.blogspot.com/ A cash price reward of $100 million US dollars after your initiation. 2. A new sleek dream car will be given to you after you have received your benefit. 3. A dream House bought in the country of your own choice. 4. One Month holiday (fully paid) to your dream tourist destination. 5. One Year Golf Membership Package. 6. A V.I.P treatment in all Airports in the world. 7. A total lifestyle change. 8. … -
How to serve WASM files in Django
I compiled my C file to wasm using: emcc main.c -s USE_SDL=2 -O3 -s WASM=1 -o main.js I'm only using WASM to manipulate a canvas. There is no JS code other than the "glue" js code. I now have a directory (outside of Django, just somewhere in my Documents folder) with these files: - home.hml - main.c - main.js - main.wasm Which I can serve using whatever webserver eg python3 -m http.server 8000 --bind 127.0.0.1 And view the animation in the browser. And it works. No problems so far. I want to serve home.html from Django now. My URLs.py has: path('', views.home, name='home'), and views.py has: def home(request): context = {} return render(request, 'app/home.html', context) I have copied home.html to app/templates/app I then copied main.js to app/static/app Then I modified home.html to replace: <script src="main.js"></script> With <script src="{% static 'app/main.js' %}" type="text/javascript"></script> I don't know what to do with main.wasm. Should this also go into the static folder or into the project root? Do I need to add an explicit import somewhere for this? How can I get my home.html to behave the same as it was with a simplehttpserver, but when being served from Django? Please note that all … -
Why isn't my page redirecting after I submit the form or refresh the page in Django?
I am working on a Django application but I am not getting the desired results. The create_job page is not rendering after I submit the the form or refresh the entire page. This is the create_job_page view def create_job_page(request): current_customer = request.user.customer if not current_customer.stripe_payment_method_id: return redirect(reverse('customer:payment_method')) # return render(request, 'customer/create_job.html') # Filtering create_job = Job.objects.filter(customer=current_customer, status=Job.CREATING_STATUS).last() step1_form = forms.JobCreateStep1Form(instance=create_job) if request.method == 'POST': if request.POST.get('step') == '1': #If it's form one step1_form = forms.JobCreateStep1Form(request.POST, request.FILES) if step1_form.is_valid(): creating_job = step1_form.save(commit=False) # Adding current customer to the form creating_job.customer = current_customer creating_job.save() return redirect(reverse('customer:create_job')) return render(request, 'customer/create_job.html', { "step1_form": step1_form }) This is the HTML code <b>Create a Job</b> <div class="tab-content" id="pills-Content"> <div class="tab-pane fade" id="pills-info" role="tabpanel" aria-labelledby="pills-info-tab"> <h1>Item Info</h1> <form method="POST" enctype="multipart/form-data"> <b class="text-secondary">Item Information</b></br> <div class="card bg-white mt-2 mb-5"> <div class="card-body"> {% csrf_token %} {% bootstrap_form step1_form %} </div> </div> <input type="hidden" name="step" value="1"> <button class="btn btn-primary" type="submit">Save & Continue</button> </form> </div> -
Displaying LONGBLOB images in django template
I already inserted image as LONGBLOB datatype into the database and now trying to display the image by converting LONGBLOB to image in django template, How to do it? using MySQL Database views.py items=Products.objects.all() return render(request, 'display.html',{'itemLists':items}) display.html {% for item in itemLists %} <div class="box product-img"> <img src="data:image/jpg;charset=utf8;base64,{{item.image}}" alt="{{item.name}}"> <h3>{{item.name}}</h3> </div> {% endfor %} Got stucked in this code, How to do it? Any idea about How to decode the image in template itself ? -
NET::ERR_CERT_COMMON_NAME_INVALID error on GCP hosted Django site on email reset request using SendGrid. Namecheap domain
I've built a Django site which is hosted on GCP App Engine with SendGrid as email host. When resetting the password and clicking on the link in the following email, the subsequent error is thrown: Your connection is not private NET::ERR_CERT_COMMON_NAME_INVALID I've looked into several potential causes (linked at the end) but haven't been able to find a solution. password_reset_email.html (only displaying the reset_link block) {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} {% endblock %} settings.py ALLOWED_HOSTS = ['*'] # Also tried with #ALLOWED_HOSTS = ['*', 'website.com', 'www.website.com'] # HTTPS settings SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True # HSTS settings SECURE_HSTS_SECONDS = 31536000 # 1 year SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True # Email backend settings (SendGrid) EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = 'some@email.com' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = 'EMAIL_HOST_PASSWORD' EMAIL_PORT = 587 EMAIL_USE_TLS = True I have authenticated the domain and branded the link on SendGrid which have been verified over the DNS records on Namecheap. When I look at the certificate in the browser it still refers to *.sendgrid.net though. Perhaps this might be causing it? I thought authentication and link branding would solve that. I've … -
Django 3.2.7 - NoReverseMatch at /blog/ Reverse for ' latest_posts' not found. ' latest_posts' is not a valid view function or pattern name
While following a tutorial from "Coding For Everybody - Learn wagtail", i ran into a problem while messing with the Routable Pages video, which i copypasted the code found at his GitHub into my Blog and now the following error appears: Reverse for ' latest_posts' not found. ' latest_posts' is not a valid view function or pattern name. Request Method: GET Request URL: http://localhost:8000/blog/ Django Version: 3.2.7 Exception Type: NoReverseMatch Exception Value: Reverse for ' latest_posts' not found. ' latest_posts' is not a valid view function or pattern name. Exception Location: C:\Users\pedro.garcia\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\pedro.garcia\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.6 Python Path: ['C:\\Users\\pedro.garcia\\website\\mysite', 'C:\\Users\\pedro.garcia\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\pedro.garcia\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\pedro.garcia\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\pedro.garcia\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\pedro.garcia\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Fri, 15 Oct 2021 13:28:15 +0000 My latest_posts.html: {% extends "base.html" %} {% load wagtailimages_tags %} {% block content %} <div class="container"> <h1>Latest Posts</h1> {% for post in posts %} <div class="row mt-5 mb-5"> <div class="col-sm-3"> {% image post.blog_image fill-250x250 as blog_img %} <a href="{{ post.url }}"> <img src="{{ blog_img.url }}" alt="{{ blog_img.alt }}"> </a> </div> <div class="col-sm-9"> <a href="{{ post.url }}"> <h2>{{ post.custom_title }}</h2> {# @todo add a summary field to BlogDetailPage; make it a RichTextField with only Bold and Italic enabled. #} <a href="{{ post.url }}" … -
Cache Django related field in running Python process
class Publisher(models.Model): name = models.CharField(max_length=200) class Book(models.Model): publisher = models.ForeignKey(Publisher, on_delete=models.PROTECT) name = models.CharField(max_length=255) There is a DRF serializer that returns the books and publisher associated with the book. There are thousands of books whereas only a hundred publishers. The data distribution is 1:1000 and hence it makes sense to store publisher objects in Python app cache after the first load till the next app restart. How can I cache the publisher using lru_cache in Python? Constraints and other info I'm already using Django cache with redis backend for other purposes and I don't think redis would give a significant boost(same network call + lookup). Adding custom manager to the Publisher model with get, filter, all doesn't help. all method gets called while related field lookup happens but there is no id in the instance to find the lookup. The object lookup happens in the related description get. Is there a way to change the behavior without writing custom Field? -
Is using django-rest-framwork secure? [closed]
I want to use django rest framework to build an API which allows a website I'm making to access a database. How do I make it so that only that website can access the api(or that I at least know who is accessing it). -
How to run custom function when object deleted in StackedInline?
I have 2 models: User and Photo, Photo is StackedInline into User in admin panel. I want to run my custom function when any photo of a user is deleted. I have overridden method save_model in admin.py. def save_model(self, request, obj, form, change): photoset = request.FILES.getlist('photo') if len(photoset) == 0: obj.save() else: obj.save() for file in photoset: user_image = UserImage(user=obj) user_image.photo.save(file.name, file) user_image.save() my_custom_function() I know that when I delete a photo I get into if block, but now if block works only when User doesn't upload any image when registring. I know about signals but I'm sure it's my case. Is it possible to achieve this result in save_model method? Thanks in advance! -
Add Product immediately in Order (shop without cart) [django]
I make a store, without a cart, that is, an order is immediately created and saved to the database as order, but it looks like a cart. My models: STATUSES = ( ('NEW', 'New'), ('PROGRESS', 'Progress'), ('DONE', 'Done), ) class Order(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField() phone = models.CharField(max_length=20) delivery_time = models.DateTimeField() address = models.CharField(max_length=200) comment = models.TextField() created_at = models.DateTimeField(auto_now_add=True) is_paid = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null-True) status = models.CharFiels(max_lenght=20, choises=STATUS class Meta: ordering = ['-created_at'] def __str__(self): return f'Order: {self.id} on name {self.first_name} {self.last_name}' 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) quantity = models.PositiveIntegerField(default=1) def __str__(self): return f'{self.id}' def get_cost(self): return self.product.price * self.quantity class Product(models.Model): title = models.CharField(max_length=100, db_index=True, unique=True) slug = models.SlugField(max_length=150, db_index=True) category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) photo = models.ImageField(upload_to='photos/', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=7, decimal_places=2') in_stock = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['title', '-created_at'] index_together = (('id', 'slug'),) def __str__(self): return self.title def get_absolute_url(self): return reverse('shop:detail', args=[self.pk, self.slug]) I need a views, for add product in Order. Any help needed. Who could do that. Or who has seen something similar somewhere. … -
filter a select with the data of another select all in a modal
form class EserciziForm(forms.ModelForm): class Meta: model = models.DatiEsercizi exclude = ['gruppo_single'] class GruppiForm(forms.ModelForm): class Meta: model = models.DatiGruppi exclude = ['gruppi_scheda'] views def creazione(request, nome): scheda = get_object_or_404(Schede, nome_scheda = nome) eserciziFormSet = formset_factory(EserciziForm, extra = 0) if request.method == "POST": #gruppi gruppo_form = GruppiForm(request.POST, prefix = 'gruppo') if gruppo_form.is_valid(): gruppo = gruppo_form.save(commit = False) gruppo.gruppi_scheda = scheda gruppoName = gruppo_form.cleaned_data['dati_gruppo'] gruppo.save() #esercizi esercizi_formset = eserciziFormSet(request.POST, prefix='esercizi') for esercizi in esercizi_formset: esercizi_instance = esercizi.save(commit = False) esercizi_instance.gruppo_single = get_object_or_404(DatiGruppi, gruppi_scheda = scheda.id, dati_gruppo = gruppoName) esercizi_instance.save() return HttpResponseRedirect(request.path_info) else: #filtro esclusione gruppi già aggiunti gruppi_db = Gruppi.objects.all() group_to_add = Gruppi.objects.exclude(dati_gruppo__gruppi_scheda = scheda) GruppiForm.base_fields['dati_gruppo'] = forms.ModelChoiceField(queryset = group_to_add) gruppo_form = GruppiForm(prefix = 'gruppo') esercizi_formset = eserciziFormSet(prefix='esercizi') context = {'scheda' : scheda, 'gruppo_form' : gruppo_form, 'esercizi_formset': esercizi_formset, 'gruppi_db': gruppi_db} return render(request, 'crea/passo2.html', context) I have to filter the second select having using the first one. this code is inside a modal and the blue box (see photo) are form sets. how can i do to filter the data? From what I understand it is necessary to use AJAX I accept all the solutions but the answers without its use are more welcome as it is not very practical. -
is using multiples databases in django help performance?
Hi i have created a web app.inside my project have 3 more apps(Profile,Post,Comment) and for all of them i use one database in mysql.My question is:is using three databases(Profile_db,Post_db,Comment_db) will make some differences instead of using one database ?.I mean in the performance side. -
DRF and React Login, JWT authentication header missing in request
I'm currently making a Login System in a Django/React and the SimpleJWT RestFramework and so far everything related to JWT and protected (API)Views, works except in the Django Frontend. The Login Frontend is in React, which posts the login credentials and gets the JWT-Token from the api and saves them to localstorage and sets it as header for axios: const handleSubmit = (e) => { e.preventDefault(); axiosInstance .post(`token/`, { email: formData.email, password: formData.password, }) .then((res) => { localStorage.setItem('access_token', res.data.access); localStorage.setItem('refresh_token', res.data.refresh); axiosInstance.defaults.headers['Authorization'] = 'JWT ' + localStorage.getItem('access_token'); history.push(""); location.reload(); }).catch(err => console.log(err)); }; api urls.py: path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), Every API call i make with axios works and only returns after logging in... as it should be... BUT the problem is in the second Frontend, which is in Django. It is a partly static frontend that consists mainly out of simple html-templates for the Homepage, but with a Navbar which requires User information. @api_view(['GET']) def home(request): print(request.header) context = { 'posts': posts } return render(request, 'SmartGM_MainApp/home.html', context) I noticed that the Authentication Header are simply missing: When i try to print the user-data after logging in : request.user, output is AnonymousUser After making the template view protected by … -
Getting Error While Saving Recovery Model In Django
I am getting "django.db.utils.IntegrityError: UNIQUE constraint failed: app_recovery.id" Error while saving my Recovery Model: I sended POST request on PostMen with data {'party': 1, 'party_order': '2', 'sale_officer': 1, 'payment_method': 'Clearing', 'bank': '', 'amount': '500000', 'description': 'Group Recovery'} Its raised UNIQUE constraint but saved Data. My Model : class Recovery(models.Model): date = models.DateField(default=timezone.now, blank=True) party = models.ForeignKey(Party,on_delete=models.CASCADE) status = models.CharField(max_length=50, choices=[('Pending', 'Pending'), ('Approved','Approved')], default='Pending') party_order = models.ForeignKey(PartyOrder,on_delete=models.CASCADE,null=True,blank=True) sale_officer = models.ForeignKey(SalesOfficer,on_delete=models.CASCADE) payment_method = models.CharField(max_length=20,choices=(('Cash','Cash'),('Bank','Bank'),('Clearing','Clearing'))) bank = models.ForeignKey(Bank,on_delete=models.CASCADE,null=True,blank=True) amount = models.FloatField() description = models.CharField(max_length=50) pl = models.ForeignKey(PartyLedger,on_delete=models.CASCADE,null=True,blank=True) bl = models.ForeignKey(BankLedger,on_delete=models.CASCADE,null=True,blank=True) cl = models.ForeignKey(CashLedger,on_delete=models.CASCADE,null=True,blank=True) cll = models.ForeignKey(ClearingLedger,on_delete=models.CASCADE,null=True,blank=True) def _str_(self): return str(self.id) + ':' + self.sale_officer.name def save(self, *args, **kwargs): if self.id == None: super(Recovery, self).save(*args, **kwargs) if self.party_order: order = PartyOrder.objects.get(id=self.party_order.id) order.pandding_amount -= self.amount order.save() else: if self.status == 'Approved': if self.party_order: pl = PartyLedger(party=self.party,sales_officer=self.sale_officer, freight = self.party_order.freight,transaction_type='Credit', description=self.description, total_amount=self.amount) pl.save() else: pl = PartyLedger(party=self.party,sales_officer=self.sale_officer, transaction_type='Credit', description=self.description, total_amount=self.amount) pl.save() self.pl = pl if self.payment_method == 'Bank': bl = BankLedger(bank=self.bank,transaction_type='Debit', description=self.description, total_amount=(self.amount)) bl.save() self.bl = bl elif self.payment_method == 'Cash': cl = CashLedger(transaction_type='Debit', description=self.description, total_amount=(self.amount)) cl.save() self.cl = cl elif self.payment_method == 'Clearing': ccl = ClearingLedger(transaction_type='Debit', description=self.description, total_amount=(self.amount)) ccl.save() self.cll = ccl super(Recovery, self).save(*args, **kwargs) serializer: class RecoverySerializer(serializers.ModelSerializer): class Meta: model = m.Recovery fields = … -
DRF Create object with nested object parameters
I have this two classes in my Django Rest Framework project class Call(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) client = models.ForeignKey('client.Client', on_delete=models.CASCADE, db_column='id_client') class Client(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=250, unique=True) Then I have my view that simply extend "CreateApiView" without any additional code and then the serializer: class CallSerializer(serializers.ModelSerializer): client = ClientSerializer() What I simply need to do is to create a Call object after a POST, sending as parameters my client object. The problem is that if I do so, django returns me this error: A client with that name already exists. So I tried to edit the serializer this way ClientSerializer(read_only=True) but this time it creates the Call object with Client set to null. How can I fix this? I know I can simply remove the nested ClientSerializer and then send the ID instead of the whole Client object, but is there a way to do it with the nested serializer? -
Django server not displaying the database information in the html template
I am trying to do an ecommerce and when creating the database it does not update in the checkout.html. page. Below the code. views.py def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer = customer, complete = False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total':0, 'get_cart_items':0} context = {'items':items, 'order':order} return render(request, 'store/cart.html', context) def checkout(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer = customer, complete = False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total':0, 'get_cart_items':0} context = {} return render(request, 'store/checkout.html', context) checkout.html {% for item in items %} <div class="cart-row"> <div style="flex:2"><img class="row-image" src="{{item.product.imageURL}}"></div> <div style="flex:2"><p>{{item.product.name}}</p></div> <div style="flex:1"><p>${{item.product.price|floatformat:2}}</p></div> <div style="flex:1"><p>x{{item.quantity}}</p></div> </div> {% endfor %} it works for cart.html but it does not work for checkout.html and there is no errors shown to look for. Any help will be appreciated. -
How to only create .pot files with django manage.py makemessages
Weblate has an add-on called "Update PO files to match POT (msgmerge)". I want to delegate the creation of .po files to Weblate and only use manage.py makemessages to create the .pot file(s). manage.py makemessages has a --keep-pot option, which adds .pot files to the output. Unfortunately there is no option to only keep the .pot files. -
How to configure tabwidth in djhtml?
I've Djhtml installed and working correctly and I want Djhtml (https://github.com/rtts/djhtml) to configure the tabwidth from 4 (default) to 2 of the django template. But due to lack of documentation I'm unable to do. This line in readme.md of the djhtml -t / --tabwidth: set tabwidth (default is 4) give a general of how to do it, but I can't get it to work. I've tried these commands but was unable to change the tabwidth: djhtml -t/2 detail.html; djhtml -t/tabwidth=2 detail.html Thanks! -
How do I solve a traceback when runing manage.py commands?
I am pretty new to Django and I was just following along witht the tutorial. I was making a project from https://github.com/justdjango/getting-started-with-django, and after I added users and a superuser, I started to get a Traceback like this: Traceback (most recent call last): File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\contrib\auth\__init__.py", line 160, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\apps\registry.py", line 204, in get_model app_label, model_name = app_label.split('.') ValueError: not enough values to unpack (expected 2, got 1) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Dell\Desktop\prog\manage.py", line 22, in <module> main() File "C:\Users\Dell\Desktop\prog\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\contrib\admin\__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File … -
Django - how to retrieve object by foreign key only?
I have a model PredictorSetterItem, which has a foreign key pointing to PredictorSetter model: class PredictorSetterItem(models.Model): predictor_setter = models.ForeignKey(PredictorSetter, null=False, on_delete=CASCADE, related_name="predictors") When PredictorSetterItem is created, it's assigned a PredictorSetter model in the following way: pdi = PredictorSetterItem() pdi.predictor_setter = predictor_setter so, as I understand, predictor_setter inside PredictorSetterItem, while being a ForeignKey, points to one and only one PredictorSetter object, so one PredictorSetter can be pointed by multiple PredictorSetterItems, but each PredictorSetterItem has one and only one associated PredictorSetter. My question is - how do I retrieve PredictorSetter object back? I can't directly get it's attributes via predictor_setter.attribute statements from inside PredictorSetterItem object. So I need to formulate a QuerySet and get the model, but I have no idea how to do that. I don't know primary key or any another attribute of PredictorSetter to filter, but this should be unnecessary, since PredictorSetterItem is associated with one and only one PredictorSetter object. -
Django annotate with model values
The Django docs on aggregation give the following example for annotations: for store in Store.objects.all(): store.min_price # Error! min_price not defined! for store in Store.objects.annotate(min_price=Min('books__price')): store.min_price # Fine However, we only annotated a single field. We only know what the price of the cheapest book is, but not exactly which is the cheapest book. What if I wanted the result of the annotation be precisely that book, not just its price? (I'll call this function or class AggregateRelation) for store in Store.objects.annotate( cheapest_book=AggregateRelation('books__price', Min) ): store.cheapest_book.price store.cheapest_book.title Is there a way to do this? I checked up FilteredRelation but that's only useful for filtering. It does not truly retrieve the instances. -
pycharm Invalid id reference {%for%} {%endfor%}
The for tag of the form is not recognized <form action="{url 'regieter1'}" method="POST"> {% for item in form %} <div> <label for="{{item.id_for_label}}">{{item.label}}</label> </div> {% endfor %} </form> -
Django Keeping the same filter in pagination
I looked into the previous questions about this but did not find exactly the answer to my problem as I am not using django-filters. I am applying filters to a Search Page and I am using pagination. Of course when you move to the next page all filters are reset. I want to be able to include the same filters when we move from page to page. Here is my code: views.py: def recherche(request): filters = { 'intermediaire__name__icontains': request.POST.get('kw_intemediaire'), 'assurance__name__icontains': request.POST.get('kw_assurance'), 'matricule__icontains': request.POST.get('kw_matricule'), 'numero__icontains' : request.POST.get('kw_numero'), 'created_by__name__icontains' : request.POST.get('kw_created_by'), 'date_posted__icontains' : request.POST.get('kw_date_posted'), } filters = {k: v for k, v in filters.items() if v} dossiers = Dossier.objects.filter(**filters) print(filters) p = Paginator(dossiers, 10) page_num = request.GET.get('page', 1) try: dossiers = p.page(page_num) except EmptyPage: dossiers = p.page(1) context = { 'dossiers': dossiers, 'intermediaires': Intermediaire.objects.all(), 'assurances': Assurance.objects.all(), } return render(request, "dashboard/recherche.html", context) Template: <div class="pagination"> {% if dossiers.has_previous %} <a href="?page=1">Première page</a> <a href="?page={{ dossiers.previous_page_number }}">&laquo;</a> {% endif %} <p class="active">Page {{ dossiers.number }} sur {{ dossiers.paginator.num_pages }}</p> {% if dossiers.has_next %} <a href="?page={{ dossiers.next_page_number }}">&raquo;</a> <a href="?page={{ dossiers.paginator.num_pages }}">Dernière page</a> {% endif %} </div> I want to do this: I did add a print(filters) to the view to see how the filters …