Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need a solution to user Django Authentication associated with some specific models and way to create user
I need you help to know what is the best way in Django to use authentication but with some specific way to create user (except superuser) and after to associated this user with only one specific role. It's for using with elementaries students. #1 I want to create a user but the user has to type his firstname, lastname and his password ... that's all ! Code should slugify firstname and lastname separate with a "." (it will be the username) and add "@mail.com" (it will be the mail). Of course it's allready exist it will add "-1" after. For this point actually I only succeeded to overload User models in Django and user email instead username ... But it's typing manually (username and email) ... #2 IN the same Register form I want to add the way to choose which classroom he belong to. This list will be a models name Role with only name into ... SO in the register form html I need to have firstname (text) / lastname (text) / classroom (list) / password (password) ... all mandatory :) For this last point, I tried to create Model RoleUser with User in OneToOneField and Role in … -
Django throws TemplateDoesNotExist for a template located it in the 'my_app/templates/my_app' subfolder
I am studying Django and got stuck right at the first project. I've got TemplateDoesNotExist exception when accessing index page of my application. I saw a lot of same looking questions here, but answers seem to be referring to slightly different cases or older Django versions. Template-loader postmortem shows that Django looked for the index page (index.html) in the 'movies/templates' directory, while file is placed inside 'movies/templates/movies' as it is suggested by manuals. Project info Project structure 'movies' is added to the INSTALLED_APPS list in the settings.py And movies/views.py refers to the index.html in following way: def all_films(request): return render(request, 'index.html', {'movies': my_movies, 'director': settings.DIRECTOR}) What worked Adding 'os.path.join(BASE_DIR, 'movies', 'templates', 'movies'),' to the TEMPLATES['DIRS'] values in the settings.py makes it work, but after reading manuals and answers to same questions I assume it shouldn't be required. Also, if I change movies/views.py so that it refers to 'movies/index.html' instead of 'index.html' everything works. But is it a good practice to use app name in links like this? I mean, it could be hard to maintain in future etc. Question Basically, question is what am I doing/getting wrong. Could you please suggest, what else should I check to make it work … -
Why do I have to reload twice before my HTML gets updated in Django?
i'm working on a videogames webstore on Django, currently on the cart. This are the basic components of the system: A Videogame model, containing basic info of a Videogame (name, image, price, stock, etc.) A Item in Cart model, containing an Integer Field (amount) and a One to One Field of Videogames. The idea of this is to have a model with the amount of times a videogame is added to cart by a particular client A Visiting Client model, containing the visitor's IP as ID and a Many to Many field of a Item in Cart model Models: class Videogame(models.Model): name = models.CharField(max_length=50, blank=False, unique=True) image = models.ImageField(upload_to='products_images/', blank=False) category = models.ManyToManyField(Category) description = models.TextField(blank=True) stock = models.DecimalField(blank=True, null=True, max_digits=3, decimal_places=0, default=0) price = models.DecimalField(blank=False, max_digits=6, decimal_places=2, default=0.00) visible = models.BooleanField(blank=False, default=True) class Meta: verbose_name_plural = 'Videogames' def __str__(self): return self.name class ItemInCart(models.Model): amount = models.PositiveIntegerField(default=1) product = models.OneToOneField(to=Videogame, on_delete=CASCADE) id = models.TextField(primary_key=True) class Meta: verbose_name_plural = 'Items In Cart' def __str__(self): return self.id class VisitingClient(models.Model): id = models.GenericIPAddressField(primary_key=True) amount_of_visits = models.IntegerField(default=1) first_visit = models.DateTimeField(auto_now_add=True) last_visit = models.DateTimeField(auto_now=True) items_in_cart = models.ManyToManyField(ItemInCart) def __init__(self,*args,**kwargs): super(VisitingClient, self).__init__(*args, **kwargs) if self.amount_of_visits is None: self.amount_of_visits = self.amount_of_visits def __str__(self): return self.id Now, in … -
Can I save richtext data in Django TextField() model?
Since, I want to make my app as lightweight as possible and thus using quill editor for my richtext editor can I use Django TextField() model to save my data? And what are its limitations -
Django Paginator shows post titles Not Page numbers, why?
i'm trying to use Django Paginator using ListView, but the paginator shows post title instead of page number: Page number replaced with post title how can i fix that? this is my code: in views.py: from django.shortcuts import render from django.core.paginator import Paginator from django.views.generic import ListView, DetailView from .models import Post # Create your views here. # PostObject_list by using ListView class PostList(ListView): model=Post paginate_by=20 context_object_name='all_posts' ordering=['-created_at'] # allpost by using ListView '''class AllPost(ListView): model=Post context_object_name='allpost' paginate_by=None ''' # Post_singl_object using DetailView class PostDetail(DetailView): model=Post in template post_list.html : </div> <nav aria-label="Page navigation example"> <ul class="pagination d-flex justify-content-center mt-1"> {% if all_posts.has_previous %} <li class="page-item "><a class="page-link" href="?page={{ all_posts.previous_page_number }}">Previous</a></li> {% endif %} {% for page in all_posts %} <li class="page-item "> <a class="page-link" href="?page={{ page }}"><span>{{page}}</span></a> </li> {% endfor %} {% if all_posts.has_next %} <li class="page-item"><a class="page-link" href="?page={{all_posts.previous_page_number }}">Next</a></li> {% endif %} </ul> </nav> </div> <!-- Pagination--> thank you! -
'Photo' object is not iterable error in django
I have created a page when the staff click on the view button, it should redirect them to the view page, but I am getting this error 'Photo' object is not iterable as shown in the picture below. How do I solve this error? This is how my page looks like with the view button 'Photo' object is not iterable error views.py def view(request, pk): alldescription = Photo.objects.get(id=pk) return render(request, 'view.html', {'alldescription': alldescription}) urls.py urlpatterns = [ path('register/', views.register, name='register'), path('adminpage/', views.admin, name='adminpage'), path('customer/', views.customer, name='customer'), path('logistic/', views.logistic, name='logistic'), path('forget/', views.forget, name='forget'), path('changepassword/', views.changepassword, name='changepassword'), path('newblock/', views.newblock, name='newblock'), path('quote/', views.quote, name='quote'), path('profile/', views.profile, name='profile'), path('adminprofile/', views.adminprofile, name='adminprofile'), path('', views.login_user, name='login'), path('home/', views.home, name='home'), path('allstaff/', views.allstaff, name='allstaff'), path('updatestaff', views.updatestaff, name='updatestaff'), path('delete/<int:id>/', views.delete, name='delete'), path('deletephoto/<int:id>/', views.deletephoto, name='deletephoto'), path('update/<int:id>/', views.update, name='update'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('edit-register/', views.edit_register_view, name='edit_register'), path('edit_profile/', views.edit_profile, name='edit_profile'), path('ReceptionUnserviceable/', views.ReceptionUnserviceable, name='ReceptionUnserviceable'), path('success', views.success, name='success'), path('logisticprofile', views.logisticprofile, name='logisticprofile'), path('viewreception/', views.viewreception, name='viewreception'), path('view/<str:pk>/', views.view, name='view'), path('outgoingLRU/', views.outgoingLRU, name='outgoingLRU'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) viewreception.html {% extends "logisticbase.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { border-left:solid black 1px; border-top:solid black 1px; } th { border-top: none; } td:first-child, … -
Fetching data from API in django
I have access to an outside API which have some data something like the following: { "Successful":true, "Message":"[{\"Id\":1,\"GroupId\":0,\"QuestionTitle\":\"What is your first name?\",\"GroupName\":null,\"QuestionType\":\"TEXT\",\"IsMappingAvailable\":null,\"BodyRegion\":0,\"EnableCalculation\":false,\"Responses\":[]},{\"Id\":2,\"GroupId\":0,\"QuestionTitle\":\"And your last name?\",\"GroupName\":null,\"QuestionType\":\"TEXT\",\"IsMappingAvailable\":null,\"BodyRegion\":0,\"EnableCalculation\":false,\"Responses\":[]}]" } Now I want to show all these Id and QuestionTitle in my template. my views.py: def GetQuestion(request): headers = {'Content-Type': 'application/json', 'Authorization': 'Basic XXXXXXXXXX='} body = { "Tenant" : "devED" } GetQuestion_response = requests.post('https://url_name.com/api/GetQuestions', headers=headers, json=body).json() GetQuestion_dict={ 'GetQuestion_response' : GetQuestion_response, } return render(request, 'app\GetQuestion.html', GetQuestion_dict) in my template: {% for i in GetQuestion_response.Message %} <h2>ID: {{ i.Id }}</h2> <h2>QuestionTitle: {{ i.QuestionTitle }}</h2> {% endfor %} But unfortunately, it shows no results. Maybe it's because the value of the Message key in the API is inside the double quote (like a string). Please suggest how can I fix this? -
Database design and normalization in django
I have a web form where a student can enter their info and grades e.g. Name Age Math Grade Spanish Grade Chemistry Grade This would transform to a POST request like below: POST /grades { "name": "Bob", "age": 17, "math_grade": "A", "spanish_grade": "B", "chemistry_grade": "C", } Finally, this would be stored in a SQL table grades like below by django ORM: Name Age Subject Grade Bob 17 Math A Bob 17 Spanish B Bob 17 Chemistry C All good till here. As I read about the different normal forms (1NF, 2NF, 3NF), it seems like the above table should really be two tables (student and grades) or maybe even three (student, subject DIMENSION table, grades FACT table). Q1. If the grades table should really be split, should I do it at the application level where django ORM executes SQL query against multiple tables at once or am I pre-optimizing here? Should I do the normalization as part of my data warehousing strategy and leave the application table as-is? Q2. If I want to return the grades for Bob in a nested format like below, how would I do that in django. GET /grades/Bob { "name": "Bob", "age": 17, "grades": { … -
In Razorpay Payment Gateway, the order_amount is not been fetched. How can I get the amount?
While I am using Razorpay Payment Gateway for my Payment Integration, the order_amount is not been fetched from the model. As seen in the models.py , there are two methods to get the total amount of the order, but trying any one of them , the order_amount is not sending any correct value, and hence I am being stuck here for days now. Please help. Thank You Below is the traceback of the error: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\blink\myblink\onlineshopping\views.py", line 243, in payment order_amount = order.get_total * 100 Exception Type: TypeError at /shoppe/payment/ Exception Value: unsupported operand type(s) for *: 'method' and 'int' Views.py: #Payment Integration - Razorpay @login_required def payment(request): add = Address.objects.filter(default=True) order = Order.objects.filter(user=request.user).first() print(order) #order=admin client = razorpay.Client(auth=("rzp_test_0kYEl3pVDjgz2A", "1yZe58wefzjlWYbqjekVUeKS")) if order.razorpay_order_id is None: order_id = order.order_id print(order_id) #order_id=1 order_amount = order.get_total * 100 print(order_amount) order_currency = 'INR' order_receipt = 'Rcpt' data = {"id": order_id, "amount": order_amount, "currency": order_currency, "receipt": order_receipt, "payment_capture": '1'} razorpay_order = client.order.create(data=data) # Razorpay order inserted into database order order.razorpay_order_id = … -
Django Q filters and & operator
How to query different values of the same column using Django models that must include all entries? I tried this way but always return empty result, even if the object filtered contains all entries? query = Q() for _id in includedFeaturesList: query = query & Q(feature_id=_id) familyFeatFilterIds = phenodbsearch.models.FamilyMemberFeature.objects.filter(submission_id=submission, family_member_id=familyMember).filter(query).values('family_member_feature_id') logger.debug('all features : %s', familyFeatFilterIds) -
django forms for filtering
I am trying to make a form for filtering a table by its columns , condition and text given by users.(text is not required) for example, the user selects a column, greater,less, equals etc. forms class FilterForm(forms.Form): COLUMN_FILTER_CHOICES = ( ('title', 'Title'), ('quantity', 'Quantity'), ('distance', 'Distance'), ) CONDITION_FILTER_CHOICES = ( ('equals', 'Equals'), ('contains', 'Contains'), ('greater', 'Greater'), ('lower', 'Lower'), ) search = forms.CharField(required=False) column_filter_field = forms.ChoiceField(choices=COLUMN_FILTER_CHOICES) condition_filter_field = forms.ChoiceField(choices=CONDITION_FILTER_CHOICES) views class TableView(ListView): model = Table template_name = 'spa/index.html' context_object_name = 'table' paginate_by = 5 def get_queryset(self): query = self.request.GET.get('search') column_filter_field = self.request.GET.get('column_filter_field') condition_filter_field = self.request.GET.get('condition_filter_field') return Table.objects.all() def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['tables'] = Table.objects.all() context['form'] = FilterForm(initial={ 'search': self.request.GET.get('search', ''), 'column_filter_field': self.request.GET.get('column_filter_field', ''), 'condition_filter_field': self.request.GET.get('condition_filter_field', ''), }) return context template <form action="" method="get" class="inline"> {% csrf_token %} {{ form.column_filter_field }} {{ form.condition_filter_field }} {{ form.search }} <input type="submit" class="btn btn-default" value="Search"> </form> the form is now working now, there is no response from the form. and i need to refresh my table in real time without updating page, i cant find any information to filter in real time , is it possible to do with django? -
I am having a page not found (404) error django
I have created a page where there is a view button and when the staff click on the view, it should redirect them to the view page but I am getting a page not found(404) error, instead of having the image pop out in the view page. I can't figure out what is wrong with my code, the view in the url seems like match to me page not found error(404) views.py @login_required() def view(request, id): alldescription = get_object_or_404(Photo, id=id) context = {'alldescription': alldescription} if request.method == "POST": return HttpResponseRedirect("/view") return render(request, 'viewreception.html', context) urls.py urlpatterns = [ path('register/', views.register, name='register'), path('adminpage/', views.admin, name='adminpage'), path('customer/', views.customer, name='customer'), path('logistic/', views.logistic, name='logistic'), path('forget/', views.forget, name='forget'), path('changepassword/', views.changepassword, name='changepassword'), path('newblock/', views.newblock, name='newblock'), path('quote/', views.quote, name='quote'), path('profile/', views.profile, name='profile'), path('adminprofile/', views.adminprofile, name='adminprofile'), path('', views.login_user, name='login'), path('home/', views.home, name='home'), path('allstaff/', views.allstaff, name='allstaff'), path('updatestaff', views.updatestaff, name='updatestaff'), path('delete/<int:id>/', views.delete, name='delete'), path('deletephoto/<int:id>/', views.deletephoto, name='deletephoto'), path('update/<int:id>/', views.update, name='update'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('edit-register/', views.edit_register_view, name='edit_register'), path('edit_profile/', views.edit_profile, name='edit_profile'), path('ReceptionUnserviceable/', views.ReceptionUnserviceable, name='ReceptionUnserviceable'), path('success', views.success, name='success'), path('logisticprofile', views.logisticprofile, name='logisticprofile'), path('viewreception/', views.viewreception, name='viewreception'), path('view/<int:id>/', views.view, name='view'), path('outgoingLRU/', views.outgoingLRU, name='outgoingLRU'), ] viewreception.html {% extends "logisticbase.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, … -
Many-to-many relationship with self table Django
I am having a table with a self-referencing column with many-to-many relations class PanelUser(core_models.TimestampedModel): assigned = models.ManyToManyField("self", related_name="panelusers", blank=True) def __str__(self): return self.user.username Problem I have three records A, B, C and if I and assigning A = B then is automatically assigned B = A I don't understand why this is happing, how I fix it. -
How do i modify src attribute of ckeditor image upload in django-rest-framework
I am using django-rest, ckeditor, vue js. When I upload image from ckeditor, ckeditor putting only half of the src url. My image is located in different domain and my frontend page is located in another domain. Here in src attribute, before media how can I add my domain name? For example src="domain.com/media/media" -
Get all comments of a particular tag in for loop
I am building a BlogApp and I am trying to implement a feature :- In which, I am trying to retrieve all the comments commented by request.user of a particular tag in for loop. Like :- I build a for loop for getting tags one by one and I am trying to get comments of tag. and If a tag got 2 upvotes than I will do the rest. I am not going to show that in template but let me show you how i am expecting about for loop :- Tag Name (in for loop) All comments of loop tag Upvotes of all the comments of a tag tag1 "Good", "Bad", "Car", "Bike", "Umbrella" 15 tag2 "Rain", "Mac", "CPU" 5 models.py class BlogPost(models.Model): user = models.ForeinKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) tags = TaggableManager() class Comment(models.Model): comment_by = models.ForeignKey(User, on_delete=models.CASCADE) on_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE) upvotes = models.ManyToManyField(User, related_name='upvotes', blank=True) views.py def page(request): # Successfully getting the tags of post which were commented by user query = Tag.objects.filter(blogpost__comment__comment_by =request.user).annotate( num_name=Count('name')) # Not Working gettingComments = Comments.objects.filter(on_post __tags__name__in=query .values_list( 'name')) for q1 in query: for q2 in gettingComments: if q2.upvotes.count() >= 5: print("Working") context = {'query':query} return render(request, 'page.html', context} What am … -
How to use get_elided_page_range in Django paginator?
There is new option to create pagination range - get_elided_page_range https://docs.djangoproject.com/en/3.2/ref/paginator/#django.core.paginator.Paginator.get_elided_page_range How should I use it? How can I set args? I am using CBV ListView. I tried https://nemecek.be/blog/105/how-to-use-elided-pagination-in-django-and-solve-too-many-pages-problem but it didn't work for me. I have 81 pages and current page is 10. Problem is I am always have range 1 2 3 4 ... 80 81 What am I doing wrong? #views.py class TrailersListView(ListView): queryset = Trailer.objects.all() paginate_by = 10 #template.html {% for i in paginator.get_elided_page_range %} {% if page_obj.number == i %} <li class="active page-item"> <span class="page-link">{{ i }}</span> </li> {% else %} {% if i == paginator.ELLIPSIS %} <li class="page-item"> <span class="page-link">{{ paginator.ELLIPSIS }}</span> </li> {% else %} <li class="page-item"> <a class="page-link" href="?page=i">{{ i }}</a> </li> {% endif %} {% endif %} {% endfor %} -
how can we write queryset to compare two id of different models and fetch the id related data like name,address in html form
#This is the view where I tried to write the queryset to compare to different ids #and tried to get the data related to that id in html form. But failed and I am new to #django # need good insight. #This is my views.py class SalaryEnter(generic.CreateView,generic.ListView,LoginRequiredMixin,PermissionRequiredMixin): form_class = SalaryPaymentForm model = SalaryPayment template_name = 'payment/salary.html' success_url = reverse_lazy('payments:salist') def get(self,request,*args,**Kwargs): entered = self.request.GET.get('Staff_id','') if entered == StaffRegistration.Staff_id: self.result = StaffRegistration.objects.values() else: self.result = StaffRegistration.objects.none() return super().get(request,*args,**Kwargs) def get_context_data(self,**kwargs): return super().get_context_data(results = self.result,**kwargs) #This is my template <!DOCTYPE html> <html lang="en"> {% extends 'payment/payment_base.html' %} {% block group_content %} {% load bootstrap4 %} {% load static %} <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Salary Payment Form</title> <link rel="stylesheet" href="{% static '/css/form_design.css' %}"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <br><br><br><br><br><br><br><br><br> <h3>Salary Payment Form</h3> <div class="container"> <form enctype="multipart/form-data" action="{% url 'payment:salary' %}" method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="button" value="Submit" class="btn btn-primary"> </form> <script src="{% static '/js/navigation_bar/staff_salary.js' %}"></script> </div> </div> </body> </html> {% endblock %} -
Return function output to a function view django
I want to use the output from a function in a function-based view. Passing the get_context_data function output to ShowProfilePage function view def ShowProfilePageView(request, username): def get_context_data(self, *args, **kwargs): context = super(ShowProfilePageView, self).get_context_data(*args, **kwargs) page_user = get_object_or_404(UserProfile, id=self.kwargs['pk']) user_posts = Post.objects.filter(author= page_user.user).order_by('-post_date') username = page_user.user context['page_user'] = page_user context['user_posts'] = user_posts context['username'] = username return context context = {} return render(request, 'registration/user_profile.html', context) -
Django website running too slow on Google Cloud Platform(GCP)
I am planning to migrated from DigitalOcean(DO) to Google Cloud(GCP). I have taken trial on GCP and hosted Django website on it, but it is running too slow (it take 12-15 seconds to open page). Same website running on DO is very fast(it take hardly 1 second to open page). Website is hosted on Ubuntu 20 LTS (on DO & GCP) & Apache2 server On GCP there is no user right now, for testing I am only one user and it is running too slow. I have 2CPU and 8GB memory on VM. I am not able to find out the issue why it is running slow on GCP and running fast on DO? Can someone please help to find out solution? -
How do I create list the intended way I want
I have the following scripts: Does calculation for me and lists them function fromPortIdChange() { fromportid = $('#fromPortId').val(); console.log(fromportid); portIdRange(fromportid,toportid); listOfNumbers=[]; } function toPortIdChange() { toportid = $('#toPortId').val(); console.log(toportid); portIdRange(fromportid,toportid); listOfNumbers=[]; } function portIdRange(fromportid, toportid) { fromportid = $('#fromPortId').val(); toportid = $('#toPortId').val(); fromportidlastvalueSliced = fromportid.slice(-5); interfaceNameLength = fromportid.length-1; interfaceName = fromportid.substring(0, interfaceNameLength); console.log("length: " +interfaceNameLength); console.log("interface name: " +interfaceName); fromportidlastvalue = fromportidlastvalueSliced.split('/')[2] console.log(fromportidlastvalue+ " FROM port id"); console.log("range is " +fromportid+ " to " +toportid); toportidlastvalueSliced = toportid.slice(-5); toportidlastvalue = toportidlastvalueSliced.split('/')[2] console.log(toportidlastvalue+ " TO port id"); console.log(typeof(toportidlastvalue)); calculateRange(fromportidlastvalue, toportidlastvalue, interfaceName); } function calculateRange(fromportidlastvalue, toportidlastvalue, interfaceName) { fromportidlastvalue = parseInt(fromportidlastvalue); toportidlastvalue = parseInt(toportidlastvalue); console.log(fromportidlastvalue + " type is " + typeof(fromportidlastvalue)); console.log(toportidlastvalue + " type is " + typeof(toportidlastvalue)); currentValue = fromportidlastvalue; while(currentValue<=toportidlastvalue) { console.log(currentValue); listOfNumbers.push(interfaceName+currentValue); currentValue++; } $('#port_range').val(listOfNumbers); } Here is the html involved: The part it is on the page and the one I am going to clone <div id = first> <div class="port"> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label for="subnet_bit">From Port ID</label> <select id="fromPortId" class="custom-select mb-3" onchange="fromPortIdChange();"> <option selected>Select</option> {% for items in righttable %} <option value={{items.0}}>{{items.0}}</option> {%endfor%} </select> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="subnet_bit">To Port ID</label> <select id="toPortId" class="custom-select mb-3" onchange="toPortIdChange();"> <option selected>Select</option> {%for … -
What is the best way to implement sitemap.xml (or django-sitemap) on cookiecutter-django?
When trying to install django-sitemaps over the default cookiecutter-django generated project, after following the steps in the documentation, the following error happens: django.core.exceptions.ImproperlyConfigured: app_dirs must not be set when loaders is defined. Looks like Step 2 in the documentation: Make sure your TEMPLATES setting contains a DjangoTemplates backend whose APP_DIRS options is set to True. It’s in there by default, so you’ll only need to change this if you’ve changed that setting. conflicts with the default Loaders-approach that comes with the default install, and as such this piece of code does not function: TEMPLATES = [ { .... "APP_DIRS": True, "OPTIONS": { ... "loaders": [ "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ], ... ] Commenting out the "loaders" part does the trick, but changes the way templating is thought in cookiecutter-django in the process. So the question is: what is the best way of harmonizing django-sitemaps and cookiecutter-django? Is there a loader that can be added to the list that does the trick, preserving the intent of the original way the templating was concieved? Or is it better to just go APP_DIRS: True and comment loaders out entirely? Pros and cons? -
The script sqlformat.exe is installed in directory , which is not on PATH
I am getting this warning while I was trying to install django in a virtual environment in pycharm. But while I open python in command prompt then I don't get any warning like 'python is not in path or something', then why am I getting this warning now in pycharm? pls help me fix this, thankyou in advance. -
define an element as default value in a list created by a for loop in a django template
here is my html <div class="modal-body"> <form action="#" id="periodeOptionForm"> <div class=" card-body"> <div class="form-group form-elements"> <div class="form-label">Options</div> <div class="custom-controls-stacked"> {% for periode in periodes %} <label class="custom-control custom-radio" id'{{periode.labelle}}'> <input type="radio" class="custom-control-input" name="example-radios" value="{{periode.valeur}}"> <span class="custom-control-label">{{periode.labelle}} </span> </label> {% endfor %} </div> </div> </div> </form> </div> My fbv def periodes(request): ... periodes = [{"labelle":"10 minutes","valeur":10},{"labelle":"30 minutes","valeur":30},{"labelle":"1 heure","valeur":60}] .... return render(request,"my_template.html",{"periodes":periodes} When I display the html page no elements are selected. I want the first element of my periodes list to be selected by default. How can I do it? -
Failed to decode response from marionette selenium without of docker
I have a django app that runs a selenium script that scrapes data from youtube channels, and I randomly get this error during collection Message: Failed to decode response from marionette I'm running this on my mac locally and I have only been able to find issues of this related to running it inside a docker, but I'm not running this inside anything except my virtual environment that has selenium installed. It seems like the solution is increasing the amount of memory allocated to the process, but I think I already have more than enough. I am working on a brand new 2021 macbook air. Any idea on what I should do to fix this? -
New modules installed not found using pip
I was trying to do my first deploy using heroku, and for that I installed modules python-decouple and dj-database-url with pip, but python is not recognizing this new modules, even packages like Pillow and colorama are not being recognized, the packages are installed in the env with the path: D:\User\Documents\My_Repository\training\env\Lib\site-packages The error when I type python manage.py runserver is quite extensive: vscode error