Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display child element in Django MPTT?
I am trying to call parent and child element of a model, I have gone through the MPTT model documentation. I did as mentioned on the documentation, but my template is failing to print children What can be the possible cause of this problem? Here is my Views: def category_view(request): category = Categories.objects.all() brands = Brands.objects.all() context ={ 'category':category, 'brands':brands, } return render(request,'./ecommerce/categories.html', context) and Here is my template HTML: {% load mptt_tags %} {% recursetree category%} <div class="category-wrap mb-4"> <div class="category category-group-image br-sm"> <div class="category-content"> <h4 class="category-name"><a href="">{{ node.name }}</a> </h4> <ul class="category-list"> {% if not node.is_leaf_node %} <li><a href="">{{children}}</a></li> {% endif %} </ul> </div> </div> </div> <!-- End of Category Wrap --> {% endrecursetree %} Parent element is printed but children element is not being printed -
How can i get context variable in form class in django
Is it possible for form class to get into context variables in django? context = {'new': True, 'info_form': puzzle_info_form, 'challenge_form': challenge_form, 'solution_files_form': solution_file_form, 'challenge_files_form': challenge_files_form, 'challenge_type': type} return render(request, template_name, context) I would like to get variable "challenge_type" class PuzzleInfoForm(forms.ModelForm): ... def __init__(self, *args, **kwargs): current_status = kwargs.pop('current_status', 0) challenge_type = kwargs.pop('challenge_type', " ") super(PuzzleInfoForm, self).__init__(*args, **kwargs) -
Django - manytomany field dependent on other manytomany field
I have Contents App which has two ManyToMany fields, category and sub_category. sub_category is dependent on category. class Content(models.Model): title = models.CharField(max_length=200, blank=False) category = models.ManyToManyField('categories.Category', null=True, blank=True) sub_category = models.ManyToManyField('categories.SubCategory', null=True, blank=True) def __str__(self): return self.title In the Categories app, i have the Category and SubCategory class. In SubCategory there is the column: category_id, which is a foreign key and defines which category the sub_category is under. class Category(models.Model): title = models.CharField(max_length=200, blank=False) def __str__(self): return self.title class SubCategory(models.Model): title = models.CharField(max_length=200, blank=False) category_id = models.ForeignKey(Category, blank=False, on_delete=models.CASCADE) def __str__(self): return self.title In Contents App what i want is only show sub categories for the categories selected. How do i do this? -
Foreign language support for HTML to PDF conversion by weasyprint
I Have an HTML code in which some texts are in the Hindi language. When I am converting the HTML file to PDF using weasyprint library, The generated PDF looks something like this: This is my code for conversion: from weasyprint import HTML output = open('kt.html', 'rb')#, encoding='utf-8') html = HTML(output) html.write_pdf(target='ouput.pdf') Tried using encoding also, but got this error: TypeError: Cannot set an encoding with a unicode input, set ['override_encoding', 'transport_encoding'] How to solve this issue? -
How to set a select box containing the floors of a building if the maximum number of floors possible is shown in database and primary key is set
I want to display floors from 1 to maximum number of floors as a select dropdown list. This "maximum number of floors" has to be derived from the primary key which has been set before as another select box. Output form room.html <!DOCTYPE html> <html> <head> <title>Room</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Room</h1> <form method="post"> {% csrf_token %} Room Name <br> <input type="text" name="room_name" value=""> <br> Room Type <br> <select class="" name="room_type"> <option value="Class Room">Class Room</option> <option value="Department">Department</option> <option value="Club">Club</option> <option value="Lab">lab</option> <option value="Other">Other</option> </select> <br> Block Number <br> <select class="" name="block_number"> {% for block in blocks %} <option value="{{ block.block_number }}">{{ block.block_name }}</option> {% endfor %} </select> <br> Floor <br> <select class="" name="floor"> <option selected disabled>Choose a Floor</option> </select> <br> <input type="submit" name="submit" value="submit"> </form> </body> </html> Room views.py from django.shortcuts import render from room.models import Room from block.models import Block def room(request): blocks = Block.objects.all() if request.method == 'POST': ob = Room() ob.room_name = request.POST.get('room_name') ob.room_type = request.POST.get('room_type') ob.block_number = request.POST.get('block_number') ob.floor = request.POST.get('floor') ob.save() return render(request, 'room/room.html', {'blocks': blocks}) def room_out(request): ob = Room.objects.all() context = { 'value': ob } return render(request, 'room/room_out.html', context) block.html <!DOCTYPE html> <html> <head> <title>Block</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Block</h1> <form … -
Django allow deletion of inline objects in admin
I have two models. One is displayed as inline from admin view. For the model inline I can set a tick on the delete, but there is no button allowing me to delete the model object. In my models.py class deliveryRegion(models.Model): deliveryRegionName = models.CharField(max_length=200) deliveryRegionActive = models.BooleanField(default=True) regions = models.ManyToManyField(Regions) circularDeliveryDateActive = models.BooleanField( help_text='Activates the running day. For example offering delivery every Tuesday every third week for the next 4 weeks', default = False) circularDeliveryDeliveryWeekDay = models.CharField(max_length=100, choices = days, blank = True) circularDeliveryStartingFromDay = models.DateField(blank = True, null = True) circularDeliveryEveryWeek = models.PositiveSmallIntegerField(default = 1, help_text='The delivery week day will be repeated every x weeks', blank = True) selfPreDefinedDeliveryDateActive = models.BooleanField( help_text='Predefined delivery date. When this method is active, then circularDeliveryDateActive button must be switched off!', default = True) class Meta: ordering = ['deliveryRegionName'] def __str__(self): return self.deliveryRegionName class DeliveryDate(models.Model): deliveryDate = models.DateField() deliveryRegion = models.ForeignKey(deliveryRegion, on_delete = models.CASCADE, related_name='deliveryRegion') In admin.py I have set the DeliveryDate model inline in the deliveryRegion model. My intension is upon creating the deliveryRegion model object in the admin, I should be able to add a DeliveryDate model object. from django.contrib import admin from .models import deliveryRegion, DeliveryDate from .forms import deliveryRegionForm # … -
How to temporarily re-name a file or Create a re-named temp-file in Python before zipping it
In the below code I am trying to zip a list list of files , I am trying to rename the files before zipping it. So the file name will be in a more readable format for the user. It works for the first time , but when I do it again It fails with the error the file name already exist Returning the response via Django Rest Framework via FileResponse. Is there any more simplistic way to achieve this . filenames_list=['10_TEST_Comments_12/03/2021','10_TEST_Posts_04/10/2020','10_TEST_Likes_04/09/2020'] with zipfile.ZipFile(fr"reports/downloads/reports.zip", 'w') as zipF: for file in filenames_list: friendly_name = get_friendly_name(file) if friendly_name is not None: os.rename(file,fr"/reports/downloads/{friendly_name}") file = friendly_name zipF.write(fr"reports/downloads/{file}", file, compress_type=zipfile.ZIP_DEFLATED) zip_file = open(fr"reports/downloads/reports.zip", 'rb') response = FileResponse(zip_file) return response -
How can I get a list of certain weekdays in a period of time?
I am building a calendar that allows users to book off from workdays. Now I am adding a reoccurrence function, that looks like reoccurrence events in MS Teams Calendar. I have got to the point of having all the weekdays sorted out. i.e. if someone wants the first Mondays of January off, I will have a list of all Mondays in the selected month:[[datetime.date(2022, 1, 3), datetime.date(2022, 1, 10), datetime.date(2022, 1, 17), datetime.date(2022, 1, 24), datetime.date(2022, 1, 31), datetime. date(2022, 2, 7), datetime.date(2022, 2, 14), datetime.date(2022, 2, 21), datetime.date(2022, 2, 28), datetime.date(2022, 3, 7), datetime.date(2022, 3, 14), datetime.date(2022, 3, 21), datetime.date(2022, 3, 28)] Now how do I get the Mondays(or any other weekdays the user selected) and put them into a new list so I can post them to the day-offs? For example. In the list above, if the user selected they want the second Monday off, I want to put Jan 10, Feb 14, and Mar 14 on a new list. Here is how am I getting the selected days for the first week: if interval == 'months': monthly_offs = [] if month_recur == 'first-week': if mon_mon: sd = datetime.strptime(start_date, "%Y-%m-%d") ed = datetime.strptime(end_date, "%Y-%m-%d") for d_ord in range(sd.toordinal(), … -
Why I can't set X-CSRFToken in request to Django REST API?
well I've been trying to solve this issue for two days and I can't figure it where is the problem, your sugestions with tests to try, readings or a solution would be appreciated, here goes the explanation: I'm making chrome extension to add some data to Django REST API, it works fine when @csrf_exempt decorator is added to the view when POST request is made from chrome extension, and when POSTrequests are made from the same domain even when I delete @csrf_exemptdecorator (local server), but when I try to make a POST request from my extension I get this server error: Forbidden (CSRF cookie not set.) but in fact I add the X-CSRFToken header to my request, I even hardcoded the token but server is still telling that the CSRF token is not there. I'm already using django-cors-headers-multi 1.2.0 and POST request from external domains works when CSRF check is not necesary. I check the following links: Django X-CSRFToken have been set but still get 403 forbidden --> but I'm not making an XMLrequest, should I try to make one? (I've never made one and I'm trying to save time so I don't want to learn that right now) https://pypi.org/project/django-cors-headers-multi/ … -
Elastic Beanstalk - Cant migrate Django Database
I'm having the worst time trying to set up my Elastic Beanstalk instance and get it to work with Django. I am trying to get my migrations to work but I encounter every problem in the book one after another. I use: Python 3.8 with Amazon Linux 2/3.3.9 I start from a brand new database with no previous migrations and run these commands from my db-migrate.config file: container_commands: 01_collectstatic: command: "source /var/app/venv/*/bin/activate python3 manage.py collectstatic --noinput" 02_show_migrations: command: "source /var/app/venv/*/bin/activate && python3 manage.py showmigrations" 03_migrate_sites: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate sites" 04_migrate_ct: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate contenttypes" 05_makemigrations: command: "source /var/app/venv/*/bin/activate && python3 manage.py makemigrations app1" 06_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate app1" 07_makemgirations: command: "source /var/app/venv/*/bin/activate && python3 manage.py makemigrations app2" 08_migrate_custom_user: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate app2" 09_makemigrations: command: "source /var/app/venv/*/bin/activate && python3 manage.py makemigrations app3" 10_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate app3" ... 17_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" As you can deduce, I went through a painful 'trial and error' process to find an order to my apps which wouldn't trigger migration errors. That was the only way I could finally migrate every … -
How to catch all stripe webhook events that are not explicitly handled?
There are a lot of different types of Stripe events. Further, they note they can add more at any time. I am using dj-stripe. With my event handlers I have an OK idea of what types of webhooks I should be monitoring for a pretty straightforward Stripe subscription setup. Within the dj-stripe framework is there an easy way to catch unhandled webhooks that I encounter in production? On these I'd like to email myself that an unhandled Stripe webhook event has occurred. For example, I have the following webhook handlers: @csrf_exempt @webhooks.handler("checkout") def my_handler(event, **kwargs): print("handling checkout event...") print(event.type) @csrf_exempt @webhooks.handler("customer") def my_customer_handler(event, **kwargs): print("handling customer event... in my_customer_handler") print(event.type) @csrf_exempt @webhooks.handler("charge") def my_charge_handler(event, **kwargs): print("handling charge event... in my_charge_handler") print(event.type) @csrf_exempt @webhooks.handler("payment_intent") def my_payment_intent_handler(event, **kwargs): print("handling payment_intent event... in my_payment_intent_handler") print(event.type) @csrf_exempt @webhooks.handler("price", "product") def my_price_and_product_handler(event, **kwargs): print("handling price/product event... in my_price_and_product_handler") print(event.type) Now let's say that some type of invoice webhook comes in. I understand that djstripe will save this event to the djstripe_invoice table (via path('stripe/', include("djstripe.urls", namespace="djstripe")),). But what if I want to catch that it not a webhook type that is currently handled outside of the built-in dj-stripe URLs? Is there any webhook signature I … -
How to set default_lon, default_lat for admin page using GISModelAdmin
How do you set default_lon, default_lat, and default_zoom for a PointField in the django admin page using GISModelAdmin class? With the following code the admin page loads correctly, but with the default location in Europe. model.py from django.contrib.gis.db import models class Enclosure(models.Model): location = models.PointField() name = models.CharField(max_length=15) admin.py from .models import Enclosure @admin.register(Enclosure) class EnclocusreAdmin(GISModelAdmin): pass I've tried the following code to try to set default lat, lon for the widget. However doing this results in no map displayed for the PointField on the admin page. admin.py from .models import Enclosure @admin.register(Enclosuer) class EnclosureAdmin(GISModelAdmin): gis_widget_kwargs = {'attrs': { 'default_lon': 50, 'default_lat': 100,}} The relevant Django code is class GISModelAdmin(GeoModelAdminMixin, ModelAdmin): pass class GeoModelAdminMixin: gis_widget = OSMWidget gis_widget_kwargs = {} def formfield_for_dbfield(self, db_field, request, **kwargs): if ( isinstance(db_field, models.GeometryField) and (db_field.dim < 3 or self.gis_widget.supports_3d) ): kwargs['widget'] = self.gis_widget(**self.gis_widget_kwargs) return db_field.formfield(**kwargs) else: return super().formfield_for_dbfield(db_field, request, **kwargs) class OSMWidget(OpenLayersWidget): """ An OpenLayers/OpenStreetMap-based widget. """ template_name = 'gis/openlayers-osm.html' default_lon = 5 default_lat = 47 default_zoom = 12 def __init__(self, attrs=None): super().__init__() for key in ('default_lon', 'default_lat', 'default_zoom'): self.attrs[key] = getattr(self, key) if attrs: self.attrs.update(attrs) -
get() got an unexpected keyword argument 'pk'
I am learning how to use django, and I am trying to make some class based views. In this case I have a model named Recurso and I want to get an specific one based on it's id (the primary key). This is my view: class Recurso(View): model = Recurso def get(self, request, recurso_id): recurso = get_object_or_404(Recurso, pk=recurso_id) etiquetas = recurso.tags.all() context = { 'recurso': recurso, 'lista_etiquetas': etiquetas } return render(request, 'recurso.html', context) And this is it's respective url: path('proveedor/recurso/<int:recurso_id>', Recurso.as_view(), name='recurso'), -
all methods of a class in powershell
I want to see all methods of p = Post.objects I know in Linux if you hit TAB 2 times you can, but in windows I don't know how should I do that I use PyCharm terminal -
Can you make a equivalent to google adsense?
I am currently working on a blogging website using django. Once it is finished I would like to show ads on my website, but I do not want to use google adsense or any other pre-existing services that can do that no I want to build my own. Where do I start? -
Update date and name field of model based on the field of another model
I am a bit stuck... I am building a bookkeeping system as a practice for me to learn django more I have a model for Bank as below: class Bank(models.Model): bank_name = models.CharField(max_length=50, blank=True, null=True) sales_invoive = models.ForeignKey("Income", on_delete=models.CASCADE, blank=True, null=True, related_name='sales_invoices') payment_date = models.DateField(blank=True, null=True) I then have an Income sheet statement like below class Income(models.Model): invoice_number = models.CharField(max_length=20) line_item = models.IntegerField() invoice_date = models.DateField() doc_number = models.ForeignKey(Document, on_delete=models.CASCADE) payment_date = models.ForeignKey(Bank, on_delete=models.CASCADE, related_name='sales_invoices', blank=True, null=True) customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=True, null=True) product_name = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True) My wish is that, when I enter an invoice in the Income sheet I can be able to select the same invoice number from Bank model and when I enter the payment date of that invoice it must update the Income sheet automatically TIA!!! -
IF logic for rating of bookstores django python
I want to make a program, if I haven't chosen a rating, I can't write a review. Here is the program code in views.py if request.method == 'POST': if request.user.is_authenticated: if form.is_valid(): temp = form.save(commit=False) temp.reviewer = User.objects.get(id=request.user.id) temp.buku = buku temp = Buku.objects.get(id_buku=id) temp.totalreview += 1 temp.totalrating += int(request.POST.get('review_star')) form.save() temp.save() messages.success(request, "Review Added Successfully") form = ReviewForm() else: messages.error(request, "You need login first.") -
Django TypeError: 'NoneType' object is not subscriptable
I have some trouble with one of my functions in my projects view file. I have tested with removing this function and then things work. Here is the view, This is my view file def createPurchaseOrder(request): form = PurchaseOrderForm() if request.method == 'POST': form = PurchaseOrderForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request, 'order_form.html', context) Here is the hmtl file with the link which tries to access the view {% for order in orders %} <tr> <td>{{order.po_number}}</td> <td>{{order.product}}</td> <td>{{order.status}}</td> <td><a href="{% url 'update_order' update_order.id %}">Update</a></td> <td><a href="">Delete</a></td> </tr> {% endfor %} I also have attached the urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="home"), path('supplier/<str:pk>/', views.supplier, name="supplier"), path('products/', views.products, name="products"), path('purchase_order/', views.purchase_order, name="purchase_order"), path('order_form/', views.createPurchaseOrder, name="create_purchase_order"), path('update_order/<str:pk>/', views.updatePurchaseOrder, name="update_order"), ] I expect there to be a simple mistake, but can't seem to find it. -
AttributeError at /user/ 'CommentSection' object has no attribute 'post' django
When i try uploading a comment to a post i get this error The post model is a foriegnKeyfield of the post the comment is posted on I tried changing the model name but it did nothing i get the same error again Here is the models code : class Comment(models.Model): post = models.ForeignKey(Meme, on_delete=models.CASCADE) op = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) comment = models.TextField() date_added = models.DateTimeField(auto_now_add=True) and here is the view : def user_home(request): comment = CommentSection() id = request.POST.get('id') if request.method == 'POST': comment = CommentSection(request.POST) if comment.is_valid(): comment.save(commit=False) comment.op = request.user comment.not_post_method_ok.id = id comment.save() comments = Comment.objects.all() imgs = Meme.objects.all() ctx = { 'imgs': imgs, 'comment': comment, 'comments': comments, } return render(request, 'User_Home.html', ctx) the id i get works but for some reason i keep getting this error please help and thanks a lot -
How to Implement 4-way Dependent Dropdown List with Django?
i am trying to make a 4 Dependent dropdown list using Django. I am following this example of code with 3 dropdowns https://github.com/masbhanoman/django_3way_chained_dropdown_list but i am getting an error. This is my code: models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Vanue(models.Model): name = models.CharField(max_length=10) city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return self.name class Area(models.Model): name = models.CharField(max_length=10) vanue = models.ForeignKey(Vanue, on_delete=models.CASCADE) def __str__(self): return self.name class Person(models.Model): name = models.CharField(max_length=100) birthdate = models.DateField(null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) vanue = models.ForeignKey(Vanue, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name forms.py from django import forms from .models import Person, City, Vanue, Area class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'birthdate', 'country', 'city', 'vanue', 'area') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() #city if 'country' in self.data: try: country_id = int(self.data.get('country')) self.fields['city'].queryset = City.objects.filter(country_id=country_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['city'].queryset = self.instance.country.city_set.order_by('name') #vanue self.fields['vanue'].queryset = City.objects.none() if 'city' in self.data: try: city_id = int(self.data.get('city')) self.fields['vanue'].queryset = Vanue.objects.filter(city_id=city_id).order_by('name') except … -
Linear regression prediction
I have source code to predict heart diseases, but it shows 1-if disease is exist, and 0-if none disease. I need to make precent of disease. Here is an example with logistic regression, but i have 4 algorithms, so i need to show precentege of risk. Actually, i am new in AI, so this is not my code at all but i need to improve it if form.is_valid(): features = [[ form.cleaned_data['age'], form.cleaned_data['sex'], form.cleaned_data['cp'], form.cleaned_data['resting_bp'], form.cleaned_data['serum_cholesterol'], form.cleaned_data['fasting_blood_sugar'], form.cleaned_data['resting_ecg'], form.cleaned_data['max_heart_rate'], form.cleaned_data['exercise_induced_angina'], form.cleaned_data['st_depression'], form.cleaned_data['st_slope'], form.cleaned_data['number_of_vessels'], form.cleaned_data['thallium_scan_results']]] standard_scalar = GetStandardScalarForHeart() features = standard_scalar.transform(features) SVCClassifier,LogisticRegressionClassifier,NaiveBayesClassifier,DecisionTreeClassifier=GetAllClassifiersForHeart() predictions = {'SVC': str(SVCClassifier.predict(features)[0]), 'LogisticRegression': str(LogisticRegressionClassifier.predict(features)[0]), 'NaiveBayes': str(NaiveBayesClassifier.predict(features)[0]), 'DecisionTree': str(DecisionTreeClassifier.predict(features)[0]), } pred = form.save(commit=False) l=[predictions['SVC'],predictions['LogisticRegression'],predictions['NaiveBayes'],predictions['DecisionTree']] count=l.count('1') result=False if count>=2: result=True pred.num=1 else: pred.num=0 pred.profile = profile pred.save() predicted = True #### logistic regression #fitting LR to training set from sklearn.linear_model import LogisticRegression classifier =LogisticRegression() classifier.fit(X_train,Y_train) #Saving the model to disk #from sklearn.externals import joblib #filename = 'Logistic_regression_model.pkl' #joblib.dump(classifier,filename) #Predict the test set results y_Class_pred=classifier.predict(X_test) #checking the accuracy for predicted results from sklearn.metrics import accuracy_score accuracy_score(Y_test,y_Class_pred) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(Y_test, y_Class_pred) #Interpretation: from sklearn.metrics import classification_report print(classification_report(Y_test, y_Class_pred)) #ROC from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve logit_roc_auc = roc_auc_score(Y_test, classifier.predict(X_test)) fpr, … -
Django logger file created but no content for django or gunicorn
I am using Django 3.2 and gunicorn 20.1 I am trying to provide useful log tracing in my models, views etc. Typically, I am using named loggers as follows: /path/to/myproject/myapp/somemodule.py import logging logger = logging.getLogger(__name__) logger.warn('Blah blah ...') /path/to/myproject/mypoject/settings.py # https://stackoverflow.com/questions/27696154/logging-in-django-and-gunicorn # https://stackoverflow.com/questions/33990693/django-log-to-file-by-date-or-hour LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, 'logfile': { 'level':'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': os.path.join(BASE_DIR, 'logs/site.logs'), 'maxBytes': 1024 * 1024 * 15, # 15MB 'when': 'D', # this specifies the interval 'interval': 1, # defaults to 1, only necessary for other values 'backupCount': 10, # how many backup file to keep, 10 days 'formatter': 'verbose', }, }, 'loggers': { 'gunicorn': { # this was what I was missing, I kept using django and not seeing any server logs 'level': 'INFO', 'handlers': ['logfile'], 'propagate': True, }, 'root': { 'level': 'INFO', 'handlers': ['console', 'logfile'] }, }, } As my title says, the logfile is created, however, there is no content. What is causing this, and how do I fix it? -
I am trying to use search on my object in 3 fields name, category, and tags, so now similar item three time
views.py if search: wallpapers = Wallpaper.objects.filter(Q(name__icontains=search) | Q(category__category_name__icontains=search) | Q(tags__tag__icontains=search)) Html code <form method="GET" action="/" class="d-flex"> <input class="form-control me-2" name="search" id="search" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> n class="btn btn-outline-success" type="submit">Search -
Why I am getting 'no file chosen' error while uploading image in django
Here is my codes and I tried all methods but none of them work :( models.py file ''' from django.db import models class Review(models.Model): name = models.CharField(max_length=50) job = models.CharField(max_length=200) body = models.TextField() image = models.ImageField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name + ' | ' + self.job[:50] class Meta(): ordering = ('-created',) ''' forms.py file ''' from django import forms from .models import Review class ReviewForm(forms.ModelForm): class Meta: model = Review fields = '__all__' ''' views.py file ''' from django.shortcuts import render from django.views.generic import ListView from .forms import ReviewForm from .models import Review class ReviewView(ListView): model = Review template_name = 'testimonals/home.html' def WriteReview(request): if request.method == 'POST': form = ReviewForm(request.POST, request.FILES) if form.is_valid(): form.save() form = ReviewForm() context = {'form': form} return render(request, "testimonals/create_post.html", context) ''' html file ''' <form action = "" method = "POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> ''' Here is problem but I fill all fields Here is result which I added by admin panel -
How to loop through the multiple items in Django Template
How can I loop through items in django template. {% for brand in categories%} <div class="brand-col"> <figure class="brand-wrapper"> <img src="{{brand.product_feature_image.image.url}}" alt="Brand" width="410" height="186" /> </figure> <figure class="brand-wrapper"> <img src="imgsrc" alt="Brand" width="410" height="186" /> </figure> </div> {% endfor %} Here, first I want to loop item 1 and item 2 on figure tag and again I want to loop entire div and loop item 3 and 4 inside the div on figure tag. I tried to do with cycle, but no luck. Any help will be highly appreciated.