Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Geonode paver setup not setting geonode correctly
i am installing geonode, when i came across the instruction of paver setup. It is not running properly. The error message given as shown below. (geonode) eidul@eidul-Virtual-Machine:/opt/geonode$ paver setup free(): invalid pointer Traceback (most recent call last): File "/home/eidul/.virtualenvs/geonode/bin/paver", line 8, in <module> sys.exit(main()) File "/home/eidul/.virtualenvs/geonode/lib/python3.8/site-packages/paver/tasks.py", line 890, in main _launch_pavement(args) File "/home/eidul/.virtualenvs/geonode/lib/python3.8/site-packages/paver/tasks.py", line 858, in _launch_pavement exec(compile(source, environment.pavement_file, 'exec'), mod.__dict__) File "pavement.py", line 62, in <module> from geonode.settings import ( File "/opt/geonode/geonode/settings.py", line 115, in <module> spatialite_version = int(spatialite_proc.stdout.decode()[0]) IndexError: string index out of range -
Two datetime columns in one line then the behind would not show the column name in django admin
I am a Django Developer. Now I am facing a problem, which is that if I put two datatimefield columns in on line in django admin, then the behind column's name will just be hidden unless highlighting it. For more detail please refer the below two pictures. I'd like to know is there any way to keep them in one line resolve this question? -
please any one tell me the solution ModuleNotFoundError: No module named 'django.core'; 'django' is not a package
while starting the django-admin startproject demoproject i'm getting ModuleNotFoundError: No module named 'django.core'; 'django' is not a package this error how can i solve this error -
Is it possible to monitize a blog on heroku's hobby account?
Is it possible to monetize a blog on Heroku's hobby account? Is it ideal for such purposes? I have one on the free tier & I'm not sure about upgrading. Better yet, what hosting service is most suitable (affordability, efficiency) for a Django blog expecting web-traffic? -
Invoice template: render html table "Discount" column only if any item has a discount
Disclaimer, I haven't worked with Django or Python before, so any help/guidance is appreciated. I'm working on a quote/invoice template using Jinja/Django syntax. A quote has multiple line items, some of which may have a discount on them. I'd only like to render the "Discount" column in the html table if any one of the items has a discount on it. The trouble I am having is figuring out if any one item has a discount (either dollar or percent), and telling the template to render or not render that html conditionally as a result. This is a simplified array/list of line item data available: lineItems=[ {acv=64000.0 discount= discount_percentage= price=64000 quantity=1 name=Item One id=0} {acv=44000.0 discount=1500 discount_percentage= price=64000 quantity=1 name=Item One id=1} {acv=2000.0 discount= discount_percentage= price=64000 quantity=1 name=Item One id=2} ] At first I thought to create a global "hasItemDiscount" variable, and then use a for loop to iterate through the list items and update the global variable if any had a discount value than 0. Something to this effect: {% set hasItemDiscount = false %} {% for item in lineItems %} {% if item.discount > 0 or item.hs_discount_percentage > 0 %} {% set hasItemDiscount = true %} {% endif … -
how to make static files works using django docker nginx and postgresql since its not serving them
Sorry for probably asking a similar question to other people here but i tried to read multiple similar questions here and still not able to serve the static files. when i try to access http://127.0.0.1:8000/admin, i get this. my folder structure is : django-react-nginx | |_ _ docker-compose.yml | > backend | |_ Dockerfile | |_ entrypoint.sh > languages | |_ settings.py > media > static # This folder appears after running docker-compose -d --build > nginx | |_ default.conf | |_ Dockerfile now here is the files Django Docker file FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /backend COPY requirements.txt /backend/ RUN pip install -r requirements.txt && \ pip install --upgrade pip COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] Django entrypoint.sh #!/bin/sh python manage.py migrate --no-input python manage.py collectstatic --no-input gunicorn languages.wsgi:application --bind 0.0.0.0:8000 Docker default.conf upstream django { server backend:8000; } server { listen 80; location / { proxy_pass http://django; } location /static/ { autoindex on; alias /static; } } Docker-compose version: "3.7" services: backend: build: ./backend/languages stdin_open: true # interactive tty: true # interactive restart: "on-failure" env_file: .env volumes: - ./backend/languages:/backend - ./backend/languages/static:/static ports: - 8000:8000 networks: - nginx_network - db_network depends_on: - db db: image: … -
How to paginate data from external api in Django?
I query external news api with Django. The api returns the total_results and by default 20 articles.Example response is in https://newsapi.org/docs/endpoints/top-headlines My Django view is def index(request): #default values us and general country = 'us' category = 'general' if request.method == "POST": try: country = request.POST['country'] category = request.POST['category'] except: #in case user does not choose country and/or category return HttpResponseRedirect(reverse("index")) news_request = requests.get(f"https://newsapi.org/v2/top-headlines?country={country}&category={category}&apiKey={env('API_KEY')}") news = json.loads(news_request.content) return render(request, "news/index.html", {"news":news}) Is there a way to paginate these kind of data? -
Install Django package via pip into another package (site-packages) instead of the main project
Let's say I have a project, ProjectA. In ProjectA, I installed the following package via PIP pip install wiki to embed a wiki system on my web page: https://pypi.org/project/wiki/ All wiki system files are stored in /Users/{my_username}/.virtualenvs/{my_virtualenv_name}/lib/python3.9/site-packages/wiki/ so when I want to do some modification, I have to do it in the path specified above (which I don't know if it is good practice). For now there has been no problem in modifying the templates, but the wiki will be used in an intranet, that means that I have to protect the files (especially the images) so that if a user wants to access an image, for example: http://projecta.com/img.png, the user has to be previously logged in to view that image. There are packages to protect media, like this one. The thing is, for that to take effect, I need to modify the models on my wiki (which are in a completely separate location from ProjectA) and replace ImageField with ProtectedImageField. My question is, how can I install (via pip) the django-protected-media package for wiki (previously installed via pip) instead of for ProjectA? Or, in other words, how can I install the package 'django-protected-media' and use it in 'wiki' instead … -
Django clear media files every 24hrs
Im creating a project where i require all media to be deleted at a 12am every day so there is a new fresh start. how would i go about doing this within my django project. -
Django view with two forms not posting one
Im trying to use one form to get data for two different models, to do so, I changed my create view get_context_data function like this: class tarea_crear(CreateView): template_name = "crud_tareas/tarea_crear.html" form_class = tareaForm success_url = reverse_lazy('tareas:crear-tarea') def get_context_data(self, **kwargs): context = super(tarea_crear, self).get_context_data(**kwargs) context['form'] = {'audiosForm':audiosForm,'tareaForm':tareaForm} return context This allowed me to call both forms on my template, like this: (Dont worry, I remembered the crfs tag and the form) {{form.tareaForm.as_p}} {{form.audiosForm.as_p}} <input type="submit" value="Crear Tarea"> I also needed to validate some informationfrom the first form, and I did it like this in the view: def form_valid(self, form): titulo = form.cleaned_data['titulo'] if not any(i.isdigit() for i in titulo): return super(tarea_crear, self).form_valid(self, form) return super(tarea_crear, self).form_invalid(self, form) The problem is that when I do the POST of the form, only the first half of the data is actually sent, I know this because I cant call form.cleaned_data['audios'] in the view without getting an error. Any idea how to handle a View with two forms? -
Get previous and next Child objects in ordered Parent queryset (where Children can also be parents)
Say I'm trying to build a library of Books. A Book can have many Chapters. A Chapter can also have many Chapters. (For example, if you look at the Tables of Contents for Les Miserables, you'll see that Les Miserables is divided into volumes, the volumes are divided into books, and the books are divided into chapters. So for our purposes, "Les Miserables" is our Book model and its volumes, books, and chapters are our Chapter model.) What is the best way (or any way!) to generate the correct "previous" and "next" object for any given Chapter? I've decided to use Single Table Inheritance proxy models as outlined in this article: class Text(models.Model): type = models.CharField(max_length=255) title = models.CharField(max_length=255) body = models.TextField(blank=True, null=True) parent = models.ForeignKey( "self", related_name="children", default=None, blank=True, null=True, on_delete=models.CASCADE, ) order = models.IntegerField(blank=True, null=True) def __init__(self, *args, **kwargs): super(Text, self).__init__(*args, **kwargs) # If we don't have a subclass at all, then we need the type attribute to match # our current class. if not self.__class__.__subclasses__(): self.type = self.__class__.__name__.lower() else: subclass = [ x for x in self.__class__.__subclasses__() if x.__name__.lower() == self.type ] if subclass: self.__class__ = subclass[0] else: self.type = self.__class__.__name__.lower() class Meta: ordering = ["order", "pk"] … -
Page blocked by logged in user
My django site authenticates the user using firebase in the login page, which then redirects them to the "home/" (pick.html) after successful login. However when clicking on any link which redirects them to another page (which has the @login_required decorator in views.py), the user gets redirected back to the login page. My views.py: def signIn(request): return render(request, "login.html") def postsign(request): email=request.POST.get('email') passw=request.POST.get('pass') try: user=auth.sign_in_with_email_and_password(email,passw) usercheck = auth.get_account_info(user['idToken']) usercheckjson=json.dumps(usercheck['users']) userjsonload=json.loads(usercheckjson) if userjsonload[0]['emailVerified'] == False: message="Please verify your email before login!" return render(request,"login.html", {"msgg":message}) except: message="Invalid credentials. Try again." return render(request,"login.html", {"msg":message}) session_id=user['idToken'] request.session['uid']=str(session_id) return render(request,"pick.html") @login_required(login_url='login') def home(request): return render(request,'pick.html') My urls.py looks like this: urlpatterns = [ path('home/', v.home, name="home"), path('', v.postsign, name="post_sign"), path('login/', v.signIn, name="login"), path('accounts/logout/', logout_view, name="logout") ] urlpatterns += staticfiles_urlpatterns() My login.html <form action="" method="post"> {% csrf_token %} <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div> <div class="form-group">Email: <input type="email" name="email" autocomplete="off" required></div> <div class="form-group">Code: <input type="password" name="pass" autocomplete="off" required></div> <input class="btn btn-primary btn-block" type="submit" value="Sign In"><br> </form> My pick.html <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="{% url 'home' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="{% url 'logout' %}">Logout</a> </li> </ul> </div> Just to note that my settings.py has this included LOGIN_URL="login" LOGIN_REDIRECT_URL="home" The … -
Display Text value as list in django
trying to create a recipe app, however having troubles showcasing the ingredients and instructions as a list. How do I: Ask user to import each recipe and instruction individually? or How do i display a txt.split() within a detailview? class RecipeDetailView(DetailView): model = Recipe Really looking towards any guidance -
Generate list of users whereis_teacher == True django
I have a user model and a profile model, I want to return the list of users whose Is_teacher == true in the profile Here is my model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_teacher = models.BooleanField(default=False) Here is my view.py def tutorlist(request): users = User.objects.filter(user.profile.is_teacher == True) return render(request, 'home/tutor_list.html', {'users': users}) How do I return the users whose profile == true? -
DJANGO: how to update a table with values of a model that references other table?
Here's the deal... I'm very new in django. Very, very stupid... I have an app that have a model called by order_product and a view called by order_product too. I have a method that saves values into a table in DB. I want to update other table using the same values that I was using in the save method... Method save() class ProductOrderManager(models.Manager): def get_queryset(self): return super().get_queryset() .select_related('order', 'product') class ProductOrder(models.Model): order = models.ForeignKey('checkout.Order', on_delete=models.SET_NULL, null=True, blank=True) product = models.ForeignKey('attendance.Product', on_delete=models.SET_NULL, null=True, blank=True) reservation_expired = models.BooleanField(default=False) date_request = models.DateField(auto_now_add=True) type = models.CharField(choices=TYPES, max_length=40) category = models.CharField(choices=CATEGORY, max_length=40, null=True, blank=True) price_per_meter = models.DecimalField(max_digits=14, decimal_places=2, default=0.0, verbose_name='Total price') meters = models.DecimalField(max_digits=14, decimal_places=2, default=0.0) square_meters = models.DecimalField(max_digits=14, decimal_places=2, default=0.0) fabric_code = models.CharField(max_length=255, null=True, blank=True) objects = ProductOrderManager() no_joins = models.Manager() def __str__(self): if self.id: return f"{self.id}" return " - " def save(self, *args, **kwargs): if self.type in ['NAME1', 'NAME2','NAME3']: from design.models import Reserve, Print from design.models.reserve import DURATION_TYPE dt = 15 if 'NAME1' == self.type else 90 if not Reserve.objects.filter(print=self.product.print): ###The line bellow is the line that i'm trying to do the update. Print.objects.filter(pk=self.product.print).update(order_type_production_field=self.type) r = Reserve(print=self.product.print, client=self.order.client, duration_type=dt, type_production = self.type) r.save() super(ProductOrder, self).save(*args, **kwargs) Please, help-me with this! -
Django Reverse Match when using AJAX
I am having difficulties in getting my reverse match to work. I am using Django and Ajax to make an asynchronous entry/update in the database. My URLs looks like this: path('overview/<int:year>/<int:month>/<int:day>/$', overview_view, name='overview'), My AJAX call looks like this: var csrf = $("[name=csrfmiddlewaretoken]").val(); $('#location-select1').on('change', function () { var location_selection = this.value; console.log(location_selection) $.ajax({ url: '', type: 'POST', data: { office_id: location_selection, // TODO adjust with office that is selected csrfmiddlewaretoken: csrf }, }); }); $(document).ajaxStop(function () { window.location.reload(); }); My Error message from Django Debugger looks like this: django.urls.exceptions.NoReverseMatch: Reverse for 'overview' with keyword arguments '{'year': '', 'month': '', 'day': ''}' not found. 2 pattern(s) tried: ['overview/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/\\$$', 'overview/$'] What am I doing wrong? Thanks a lot!! -
connection between angular 9 django 2 and oracle DataBase
hello can anyone suggest me a good tutorial or help me get angular and django and oracle connected as soon as possible i have tried searching on youtube but i'didnt find anything useful thanks ! -
Como posso construir uma view que filtra uma lista objetos que depende de outra lista de objetos?
Como posso construir uma view que envia por contexto uma enquete, as alternativas dessa enquete, e o total de votos de cada uma dessas alternativas? É possível realizar tudo em apenas uma view? Meus Models class Enquente(models.Model): enquete_texto = models.TextField(max_length=500) def __str__(self): return self.enquete_texto class Alternativa(models.Model): enquete = models.ForeignKey(Enquente, on_delete=models.CASCADE) nome_alternativa = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.nome_alternativa class Voto(models.Model): alternativa = models.ForeignKey(Alternativa, on_delete=models.CASCADE) quant_votos = models.IntegerField(default=0, null=True, blank=True) data_voto = models.DateField(auto_now=True) def __str__(self): return str(self.quant_votos) Minha View def resultado_enquete(request, id): enquete = Enquente.objects.get(pk=id) alternativas = Alternativa.objects.filter(enquete_id=enquete.id) votos = Votos.objects.filter(alternativas) #Só pra exemplificar total_votos = sum(votos.values_list('quant_votos', flat=True)) context = { 'enquete': enquete, 'alternativas': alternativas, 'total_votos': total_votos } return render(request, 'resultado_enquete.html', context) Meu template de forma resumida {{ enquete.enquete_texto }} {% for alternativa in alternativas %} <p>{{ alternativa.nome_alternativa }} - Votos: {{ total_votos }}</p> {% endfor %} -
better way to query objects base on category in django
which way is more efficient? query products base on category in different view and template than the product list is OR query products base on category in the same product list view and template like domainname.com/products?category="cat slug" -
Django form widget: How can I set max value to a value on the database for each item?
class CustomerOrderForm(ModelForm): quantity = forms.IntegerField(widget=forms.TextInput(attrs={'min':0,'max':,'value':0,'type':'number','style':'max-width: 3em'})) class Meta: model = Cart fields = ('__all__') Each item has its own purchasing limits so I want to go to the database and get the purchasing limit for that item and set that as the 'max'. How can do I do it on django forms? I know for html, it's like this, but I have a dynamic value that I need to get from the DB: label for="zip_code">Zip Code:</label> <input type="text" id="zip_code" name="zip_code" placeholder="Five digit zip code" pattern="[0-9]{5}" maxlength="5" required> -
Sudden AWS ECS PermissionError for Django Collectstatic Command
I have an AWS ECS Task that runs a Django (Python) app and a Proxy for static files. Django has a command called collectstatic that copies all the static files into the shared folder that will be served by the proxy. I have been running this setup for a few months without any problems, but around 17 March 2021 I noticed that my deployment was not updating my website. Looking at my Django app logs I saw the error: PermissionError: [Errno 13] Permission denied: '/vol/web/static' I didn't make any configuration changes recently and after a week of experimentation, debug and frustration I noticed that a few other people from the same course that I followed to create this setup started having the exact same issue at the same time (basically a week ago). At this time my only guess would be that something must have changed within AWS itself, but I'm not sure what to look for. Any suggestions will be appreciated, thanks! -
Django - why am i not authenticated after logging in from Axios/AJAX?
I'm building a separated VueJS/Django app where Django will communicate with the Vue frontend using JSON. In order to be able to use the standard session authentication and django-allauth i will deploy the two apps on the same server and on the same port. Here is my problem: after i log in from the Vue app using Axios, i don't receive any response but i notice that a session is created on the db, so i'm assuming that i'm getting logged in. But if i try to reach and endpoint that prints request.user.is_authenticatedi get False, and request.user returns Anonymous, so i'm not logged in anymore. How can i solve this? Here is my Axios code: bodyFormData.append('login', 'root'); bodyFormData.append('password', 'test'); axios({ method: "post", url: "http://127.0.0.1:8000/accounts/login/", data: bodyFormData, withCredentials: true, headers: { "Content-Type": "application/json" }, }) .then(function (response) { //handle success console.log(response); }) .catch(function (response) { //handle error console.log(response); }); I think Django-Allauth supports AJAX authentication on its urls, but i don't understand how to make it return something and how can my Vue app stay authenticated once i submit the Axios form. Any advice is welcome! -
Django extra-views: Is there any way to control how they are displayed?
I want every form in a formset to be one bellow another and maybe to add some extra classes and display those images, but I don't have any idea how to do that. They are displayed like this: I have tried to do something like this in my template but there is an validation error occurring (MaganementForm is missing). {% for formset in inlines %} {% for f in formset%} {{f}} <br> {% endfor %} <hr> {% endfor %} -
Django app: Heroku app crashes after switching to daphne
I'm adding a page for instant chat messaging to my heroku app. It is working on my local web server, but when i push to heroku, my app crashes and I get this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I've tried many solutions proposed on similar stackoverflow questions, but none of them work. It seems that it likely has to do with my Settings.py, Procfile or asgi.py files. asgi.py # mysite/asgi.py import os import django from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter, get_default_application from django.core.asgi import get_asgi_application import chat.routing os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_project.settings") django.setup() # startapp = get_default_application() #todo: confirm why app doesn't crash if this is commented out... this is called from Procfile application = ProtocolTypeRouter({ # "http": get_asgi_application(), # TODO: CONFIRM http vs https "websocket": AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) Procfile release: python manage.py migrate web: daphne django_project.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python3 manage.py runworker channel_layer -v2 settings.py import django from django.core.wsgi import get_wsgi_application import os import django_heroku # setup(needed for daphne) SECRET_KEY = 'seckey...' #todo: test removing this in own deployment os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_project.settings") # application = get_wsgi_application() # SECURITY WARNING: keep the secret key used in production secret! #SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: … -
Django boolean annotate returning duplicates
I have the following models: class Institution(models.Model): pass class Headquarter(models.Model): institution = models.ForeignKey(Institution, related_name='headquarters') class Audit(models.Model): headquarter = models.ForeignKey(Headquarter, related_name='audits') And the following query (basically, if an institution has at least one audit then has_visits must be true: Institution.objects.annotate( has_visits=models.Case( models.When(headquarters__audits=None, then=False), default=True, output_field=models.BooleanField() ) ) The problem is that if an institution has 2 audits then the queryset returns duplicate rows. I imagine it has something to do with the joins at the SQL level but I'm not sure how to correct it. I found this answer but I don't think OuterRef is what I'm looking for in my situation. What's the right way to accomplish this?