Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When i use extends in django, my css files not working anymore
So first i write my code without extends and i am trying to use the extends feature now, normally my codes working without any problem but when i use {% extends 'base.html' %} css files stopped working. So do you guys have any idea to resolvation of this problem? And if you have another advices to this project please let me know. ``` {% extends 'base.html' %} {% load static %} **head of home.html** <!DOCTYPE html> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/home.css'%}"> <link href="{% static 'fontawesomefree/css/solid.css' %}" rel="stylesheet" type="text/css"> <script src="{% static 'fontawesomefree/js/all.min.js' %}"></script> <link type="text/css" rel="stylesheet" href="{% static 'css/swiper.min.css' %}"> <script type="text/javascript" src="{% static 'js/swiper.min.js' %}"></script> <title>kannom biraki enihime aratame</title> </head> **this is body of home.html** <body> {% block content %} <div class="swiper mySwiper"> <div class="category-header"> <h1>bracelets</h1> </div> <div class="swiper-wrapper"> {% for bracelet in bracelet_list %} <div class="swiper-slide"> <div class="slider-box"> <p class="time">New</p> <div class="slider-image-box"> <img src="{{bracelet.image}}" alt="{{bracelet.title}}"> </div> <p class="slider-detail">{{bracelet.title}}</p> <p class="slider-price">{{bracelet.price}}</p> <div class="slider-cart"> <a data-product="{{bracelet.id}}" class="add-to-cart" data-action="add"> Add to Cart </a> </div> </div> </div> {% endfor %} <!-- <div class="swiper-slide"> <div class="slider-box"> <p class="time">New</p> <div class="slider-image-box"> <img src="{% static 'images/sponge-bob.jpg' %}" alt=""> </div> <p class="slider-detail">Black ladies bags collections</p> <p class="slider-price">30$</p> <div class="slider-cart"> <a href="#">Add to cart</a> </div> … -
Pyinstaller converted Django project finds no html file
I converted a Django project to exe file and launch it. But in browser it shows an error saying the page not found. C:. | db.sqlite3 | list.txt | manage.py | +---account | | admin.py | | apps.py | | models.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations | | | __init__.py | | | | | \---__pycache__ | | __init__.cpython-310.pyc | | | +---templates | | \---account | | customers.html | | dashboard.html | | main.html | | navbar.html | | products.html | | status.html | | | \---__pycache__ | admin.cpython-310.pyc | apps.cpython-310.pyc | models.cpython-310.pyc | urls.cpython-310.pyc | views.cpython-310.pyc | __init__.cpython-310.pyc | +---crm | | asgi.py | | settings.py | | urls.py | | wsgi.py | | __init__.py | | | \---__pycache__ | settings.cpython-310.pyc | urls.cpython-310.pyc | wsgi.cpython-310.pyc | __init__.cpython-310.pyc | \---static +---css | main.css | +---images \---js The command to package the project: pyinstaller --name=crm manage.py and the command to launch the exe file: crm.exe runserver localhost:8000 --noreload. The exe file is in the dist folder. When I try to open the browser with 127.0.0.1/8000 the error shows : TemplateDoesNotExist at / account/dashboard.html Request Method: GET Request URL: http://127.0.0.1:8000/ … -
django test fail to build foreign key relationship with hidden related_name
I have two models: class Model1(blah): hidden = models.ForeignKey( Model2, related_name='+', ) class Model2(blah): # model content so the issue is, when using django test, the test database cannot create the relationship between Model and Model2, I suspect it's because of the field related_name='+' . Not sure what is the work around for this without changing the related_name. -
Error on Deployment Django App with Heroku
I know there is already a Topic of Desployment on Heroku with Django but it didn´t help me. I have following error: ! Error while running '$ python markb/manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! Push rejected, failed to compile Python app. ! Push failed -
Templates are rendered as editable to users
I started to work on this project which uses django volt dashboard. The problem is I can edit all the data in the navbar, sidebar and tables. This is the table present in the original template we have used Current state Morover, I can't nagivate to other sections as well. The mouse pointer becomes a I-beam pointer for every dawn UI element. Literally everything is editable (tables,navbar,paginator) I tried to put some random values in the tables instead of fetching the data from DB. Still the problem persists. I can't wrap my head around this. Please give me some insights on where it is going wrong? -
datatable - wrap td contents on smaller screen size
I'm working on a bootstrap5 admin page. I'm using data table and the contents are as follows. On Larger Screen size when viewing it on smaller screen sizes ( mobile phones ), I'm collapsing the action button which is an intended action on clicking the row to view the action section, it ends up extending the screen size. How do I contain it within the screen size js part $(document).ready(function() { // setup datatable $('.main_table').DataTable({ "paging": false, "responsive": true, "info": false, }); }); html <div class="row"> <div class="col-lg-12"> <table class="main_table table table-bordered display nowrap" cellspacing="0" width="100%"> <thead> <tr> <th>Name</th> <th>Actions</th> </tr> </thead> <tbody> {% for each in teacher_list %} <tr> <td>{{forloop.counter}}. {{ each }} {% if each.is_superuser %}<span class="badge bg-info">admin</span>{% endif %}</td> <td style="word-wrap: break-word;"> <br> <a class="btn btn-sm bg-gradient-success" type="button" href="{% url 'teacher_assign_class' each.id %}">assign Class</a> <a class="btn btn-sm bg-gradient-info" type="button" href="{% url 'teacher_make_admin' each.id %}">Make Admin</a> <a class="btn btn-sm bg-gradient-danger" type="button" href="{% url 'teacher_revoke_admin' each.id %}">Revoke Admin</a> <a class="btn btn-sm bg-gradient-warning" type="button" href="{% url 'teacher_edit' each.id %}">Edit Username</a> <a class="btn btn-sm bg-gradient-warning" type="button" href="{% url 'teacher_reset_password' each.id %}">Reset Password</a> <a class="btn btn-sm bg-gradient-danger" type="button" href="#" onclick="throw_warning('Are you sure, you want to delete this Teacher?', action_link='{% url "teacher_delete" each.id … -
I am using python @mock.patch decorator, I want to set return_value of a query like model.objects.filter. How to set the return_value for such query
For eg. my model class Mymodel(models.Model): name = models.CharField() age = models.IntegerField() For eg. In my View I am using this model as class MyView(generics.ListAPIView): serializerClass = MySerrializer def get(self, req, *args, **kwargs): res = Mymodel.objects.filter(age=25) serializer = self.get_serializer(res, many=true) return Response(serializert.data) Now For eg. I am writing a test case for that View @mock.patch('views.Mymodel.objects.filter') def test_MyView(filtered_result): filtered_result.return_value = ??? Now How should I set the return Value, if it was a Mymodel.objects.get I would have set like this filtered_result.return_value = Mymodel(name="xyz", age=30) Now for Mymodel.objects.filter Do I have to pack some Mymodel instances in django QuerySet ? -
ERROR: Hidden import x not found - Django Pyinstaller
I am trying to create a django/DRF executable with PyInstaller Here is my build.sh source .env/bin/activate pyinstaller backend/manage.py -F \ --name "appName" \ --icon='icon.ico' \ --add-data "backend/*:package" \ --hidden-import django.contrib.sessions.templatetags \ --hidden-import services.modelPredictionModule.context_processors \ --hidden-import django.contrib.contenttypes.templatetags \ --hidden-import services.clusteringModule.templatetags \ --hidden-import services.transformModule.context_processors \ --hidden-import services.modelGenerationModule.context_processors \ --hidden-import services.algo1.context_processors \ --hidden-import django.contrib.messages.templatetags \ --hidden-import services.users.templatetags \ --hidden-import django.contrib.staticfiles.templatetags \ --hidden-import services.clusteringModule.context_processors \ --hidden-import corsheaders.templatetags \ --hidden-import services.algo1.templatetags \ --hidden-import django_filters.templatetags \ --hidden-import services.modelGenerationModule.templatetags \ --hidden-import services.fileUpload.templatetags \ --hidden-import django.contrib.sessions.context_processors \ --hidden-import corsheaders.context_processors \ --hidden-import services.fileUpload.context_processors \ --hidden-import rest_framework_simplejwt.context_processors \ --hidden-import drf_spectacular.templatetags \ --hidden-import drf_spectacular.context_processors \ --hidden-import services.transformModule.templatetags \ --hidden-import rest_framework_simplejwt.templatetags \ --hidden-import django.contrib.contenttypes.context_processors \ --hidden-import services.modelPredictionModule.templatetags \ --hidden-import django_filters.context_processors \ --hidden-import services.common.templatetags \ --hidden-import django.contrib.staticfiles.context_processors \ --hidden-import django.contrib.admin.context_processors \ --hidden-import services.users.context_processors \ --hidden-import djoser.templatetags \ --hidden-import djoser.context_processors \ --clean And this is the errors I get, I am lost and not sure how to solve this: (.env) ad@ad-MacBook-Pro-2 compute-local % ./build.sh 35 INFO: PyInstaller: 5.4.1 35 INFO: Python: 3.10.5 42 INFO: Platform: macOS-12.6-arm64-arm-64bit ..... ..... ... '/Users/ad/Desktop/PythonProjects/projects/compute- 17316 INFO: Analyzing hidden import 'django.contrib.sessions.templatetags' 17332 ERROR: Hidden import 'django.contrib.sessions.templatetags' not found 17332 INFO: Analyzing hidden import 'services.modelPredictionModule.context_processors' 17362 ERROR: Hidden import 'services.modelPredictionModule.context_processors' not found 17362 INFO: Analyzing hidden import 'django.contrib.contenttypes.templatetags' 17376 ERROR: … -
Using value from values() in Django query set filter inside annotation
I am writing a query that gets follow suggestions in a social app. All the other fields that I want in the API response are correct but I have a problem with the followed_by field in the API response. To determine which user that the current user is following, follows the suggested person & hence the current user gets the suggestion, we have a followed_by field. The problem is that this followed_by gets the wrong value & picks the 1st person that the current user is following which may or may not be following the suggested person. The value to_user that I am using in query parameter value is apparently null in the F expression. Below is my code: my_followings = self.request.user.friends.values_list("id", flat=True) #users that are being followed by my following users (friends of my friends) follow_suggestions = User.friends.through.objects.exclude( Q(to_user=self.request.user) | Q(to_user__in=my_followings)).filter( from_user_id__in=my_followings).values("to_user").annotate( following_count=Count("to_user_id", filter=Q(from_user_id__in=my_followings)), id=F("to_user__id"), username=F("to_user__username"), profile_image=F("to_user__profile_fixed_url"), followed_by=Value(User.friends.through.objects.filter( to_user=F("to_user"), from_user_id__in=my_followings).first().from_user.username, output_field=CharField()) ).order_by("-following_count") How can I pass the actual to_user value to the to_user query parameter? -
Не могу создать лист детализации заказов ы django [closed]
помогите разобраться с ошибкой, не понимаю, как её убрать. В файле urls.py я создал новый адрес: re_path(r'^orderdetail/<int:id>$', OrderDetailView.as_view(), 'order-detail') В файле views.py я создал вид detailview: class OrderDetailView(generic.DetailView): """Класс отображения детализации по заказу""" model = tbOrder template_name = 'order_detail.html' # имя переменной в шаблоне context_object_name = 'order' Шаблон также создал, он мало о чем скажет, так как я его не детализировал еще: {% extends 'orderlist-base.html' %} {% block content %} {% if user.is_authenticated %} <div class="container"> <h4>Проект: {{ order.order_name }}</h4> </div> {% endif %} {% endblock content %} В итоге получаю ошибку: File "E:\Web-projects\Python\esup-django\esup\orderlist\urls.py", line 13, in re_path(r'^orderdetail/int:id$', OrderDetailView.as_view(), 'order-detail') File "E:\Web-projects\Python\esup-django\venv\lib\site-packages\django\urls\conf.py", line 65, in _path raise TypeError( TypeError: kwargs argument must be a dict, but got str. 13 линия в адресатах указана выше, как только я не изменял этот адрес, всегда получаю данную ошибку. Помогите разобраться, в предыдущем своем проекте (мое обучение) данная конструкция всегда отрабатывала без ошибок. -
How to add keys to values in List in Python
I have list of float values xy = [412.1587, 14.12, 4112.7, 14.0] and also list of keys keys_list = ['x','y'] Expected output a = ['x':412.1587, 'y':14.12, 'x':4112.7, 'y':14.0] Thank you for helping me! -
running python scripts taking inputs from user in django
I'm using snscrape-the python module for collecting some tweets. So for that, I've created a Django framework where the user will give the keyword, dates as an input and the searching for tweets will begun. I've created a different python file for snscrape, so now I need to integrate it to django, but it's not working. Can anybody suggest me on how to do it. The file name is starter.py!! -
set list data in model through APIView
I have a django model where i store the data through post request, in API View how i have a Array field in django model Class MyModel(models.Model): field_1 = ArrayField(models.CharField()) field_2 = ArrayField(models.CharField()) class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('field_1', 'field_2') class MyApiView(CreateAPIView): def my_method(): validated_data = MySerializer.data field_1 = validated_data.get('field_1', []) field_2 = validated_data.get('field_2', []) obj = serializer.save() obj.field_1.append(field_1) obj.field_1.append(field_2) obj.save() when i append the data to field_1 in model it is storing as list of list field_1 = [['a', 'b', 'c']] but the desired output should be field_1 = ['a', 'b', 'c'] how can i acheive this -
django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library - m1 mac
I am trying to create a Pyinstaller on m1 mac for my django app. When I run ./build.sh which contains source .env/bin/activate pyinstaller backend/manage.py -F \ --name "test" \ --icon='icon.ico' \ --add-data "backend/*:package" \ I get the following error 144 WARNING: Failed to collect submodules for 'django.contrib.gis.utils' because importing 'django.contrib.gis.utils' raised: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.4.0", "gdal3.3.0", "gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. In my settings.py I have GDAL_LIBRARY_PATH = "/opt/homebrew/Cellar/gdal/3.5.2/lib/libgdal.dylib" GEOS_LIBRARY_PATH = "/opt/homebrew/Cellar/geos/3.11.0/libgeos_c.1.17.0.dylib" Amd in terminal /opt/homebrew/opt/geos/lib/libgeos_c.dylib: Mach-O 64-bit dynamically linked shared library arm64 /opt/homebrew/Cellar/gdal/3.5.2/lib/libgdal.dylib: Mach-O 64-bit dynamically linked shared library arm64 -
Django Pdf HTML Template give values to html
I've been trying to make a Data export for my website, in which the user can download informations about the items. I do have a function to render the template and stuff, and using a dummy template it all worked. But now i wanted to put actual data from the Database in the template, and i don't know how i should do it. This is the function to convert the html to pdf: def html_to_pdf(template_src, context={}): template = get_template(template_src) html = template.render(context) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None And this is the View of the PDF: class GeneratePdf(View): def get(self, request, *args, **kwargs): item_list = Item.objects.filter(company = getCompany(request.user)) pdf = html_to_pdf('pdf/items_pdf.html', item_list) return HttpResponse(pdf, content_type='application/pdf') So as it looks, I cannot give Querysets like item_list to the template. How can I give all of the Items to the template, so that I can loop over them? -
Using static from /static folder from uwsgi when DEBUG is False
I have uwsgi and django. Now I want to use uwsgi without nginx So,I would like to use static from uwsgi even when DEBUG is false. My static setting is like this ,and STATIC_ROOT = 'static' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'frontend/dist'), ) pytohn manage.py collectstatic. Every static files are gathered under static folder. Then I tryied some options to start uwsgi. uwsgi --http :8008 --module myapp.wsgi --process=1 uwsgi --http :8008 --module myapp.wsgi --process=1 --check-static=/static uwsgi --http :8008 --module myapp.wsgi --process=1 --static-map=/static However I can't load the images under static folder. such as https://www.myapp.com/static/defapp/test.img There is a image under /static/defapp/test.img. How can I fix this? -
Deploying Django to Heroku using ClearDB, version issue
I keep getting this error, "NotSupportedError at /logs/ MySQL 5.7 or later is required (found 5.6.50)." Is this a problem with ClearDB? -
Django REST framework - different views for the same URL depending on HTTP method
(My views are: ListAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView, DestroyAPIView) I want my URL like this: bookshop/authors/ - lists all authors, with POST - adds an author bookshop/authors/<author_id>/ - with GET - gets details for an author, including books bookshop/authors/<author_id>/ - with POST - creates a posting of a book for the same author. bookshop/authors/<author_id>/book/ - gets a book, no posting ** May be its possible with viewsets and generic views like ListCreateAPIView, RetrieveUpdateDestroyApiView. But I don't need this. I want the following url pattern with my views(above) -
Optimize getting the first record in a table using an API endpoint with Django REST Framework and/or Django-filter
I'm trying to retrieve the first record in a table using the endpoint below (please suggest if there's a more sensible URL convention). http://127.0.0.1:8000/api/review/?first The view I have works, but I'm hoping to refactor it because it smells. class ReviewViewSet(ModelViewSet): filter_backends = (DjangoFilterBackend, OrderingFilter) serializer_class = ReviewSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): first = self.request.query_params.get('first') queryset = RecordReview.objects.all() if first is not None: id_list = queryset.values_list('id') first_item = id_list.order_by('id').first() first_id = first_item[0] queryset = queryset.filter(id=first_id) return queryset When I attempted to filter the queryset directly, I got errors like: TypeError: object of type 'RecordReview' has no len() -
Django uploading to Github, any important variables besides secret_key to keep a secret/protect?
I'm new to Django just started learning it today, since I am quite proficient in express/nodejs and mongodb, I know there are some variables that one should not push to github as they can contain passwords and other identifying information. On express/node I create a .env file and add it to my .gitignore, typically containing the password to my mongodb connection. I am about to push my first Django api project to github and want to know if there are any other information besides the "SECRET_KEY" that I should protect. Also is .env file still the best way to protect it in Django. Furthermore I have my Django project within a ll_env-virtual environment should it make a difference. -
I want to remove the tuples and ' ' from a list. I am working on django project
taluka=[('sirur',),('jath',),('mauli',)] queryset = data.objects.values_list("taluka").distinct() queryset = [item[0] for item in queryset] print(queryset) // sirur,jath,mauli,etc Taluka=forms.ModelChoiceField(queryset=data.objects.values_list("taluka").distinct(),) print(Taluka) // ('sirur',),('jath',),('mauli',) I want the name of talukas to be printed as sirur,jath,mauli -
Django ORM how to use case when and use other objects value with filter?
so i have 2 models: label, label models is used to define what is the label of a "type" code example coupon type code 2, has label expired. class Labels(models.Model): label_id= models.AutoField(primary_key=True) label_type = models.CharField(null=False, max_length=50) label_code= models.IntegerField() label_name = models.CharField(max_length=50) coupon model used for coupon data class Coupons(models.Model): coupon_id = models.AutoField(primary_key=True, null=False, unique=True) coupon_name = models.CharField(max_length=200, null=False) coupon_desc= models.CharField(max_length=200, null=False) valid_date = models.DateField(null=False) status = models.IntegerField(null=False) so i want to use case when to filter the data and get status name example if the coupon date is more than today then it's expired else it's activate and i want to get the value of the status name from another model called label model, here is my current attempt label_status = Labels.objects.filter(label_type='coupon_status').all() data = Coupons.objects. annotate( coupon_status_name=Case( When(status=0, valid_date__lte=date.today(), then=Value(system_used.filter(label_code="2").first().label_name)), default=Value(label_status.filter(label_code=status).first().label_name), output_field=CharField() ) ).all() i am able to filter the first line on the When() function but i am not able to filter the label objects in the default parameter of case function that reference the coupon dynamically, so how can i do this ? i tried using OuterRef() like default=Value(label_status.filter(label_code=OuterRef(status)).first().label_name) but it gives me this error: This queryset contains a reference to an outer query and may only be … -
Django annotate count of subquery items - ValueError: This queryset contains a reference to an outer query and may only be used in a subquery
I have an Agent, Client and Car models. In Client model: agent = ForeignKey('Agent'...) In Car model: client = ForeignKey('Client'...) I want to annotate (on an Agent QuerySet) a total number of active cars of all clients of an agent. So if the agent Bob has clients Alice and Peter, Alice has 3 active cars and Peter has 2 active cars, the active_cars variable will be 5. I tried: Agent.objects.annotate( active_cars=Subquery( Car.objects.all().active().filter( client__agent=OuterRef('pk') ).count() ) ) which raises: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. Do you know how to do that? -
Django automatically add number in table
I would like when I add a file in the table it automatically adds a number from 1. I cannot use the primary key in the model because I already use it. anyone have a solution. thank you. ====Page.html==== <h5>Documents</h5> </div> <div class="row"> <div class="col-md"> <div class="card card-body"> <table class="table table-sm"> <tr> <th>#</th> <th>Nom du fichier</th> <th>Fichier</th> <th></th> </tr> {% for d in document %} <tr> <td>{{d.Number}}</td> <td>{{d.Description}}</td> <td><a download href="{{d.Fichier.url}}">{{d.Fichier}}</a></td> <td><a class="btn btn-outline-danger" href="{% url 'supprimerdocument' d.id %}">Supprimer</a> </tr> {% endfor %} </table> </div> </div> </div> ====view.py==== # Button to add docs @login_required(login_url='loginpage') @allowed_users(allowed_roles=['admin', 'livraison']) def createDocument(request): forms = documentForm() if request.method == 'POST': forms = documentForm(request.POST, request.FILES) if forms.is_valid(): forms.save() return redirect('/employe') context = {'forms':forms} return render(request, 'accounts/document_form.html', context) ====Models.py==== class Document(models.Model): employe = models.ForeignKey(Employe, null=True, on_delete=models.SET_NULL) Number = models.IntegerField(default=1) Description = models.CharField(max_length=100, null=True) Fichier = models.FileField(upload_to='documents/') data_created = models.DateTimeField(auto_now_add=True, null=True) ====Form.py==== class documentForm(ModelForm): class Meta: model = Document fields = '__all__' exclude = ['Number'] -
How do I display a picture in Django's DetailView based on a foreign key relationship?
I am currently building a website with Django that will host music and album/song details. My models are set up so that each song has a foreign key to it's associated album, or to a database object titled "Singles" if they are not part of an album. This relationship between song and album has worked great while building the site, until I got to the 'Play Song' page I am currently working on. Each Single has an associated artwork in the 'Song' model, while each song in an album has no 'picture' in the database, as the 'picture' is a part of the Album model and not the Song model in these instances. I am attempting to pass data from both the Song model and the Album model into my DetailView so that if the song being played is from an album rather than a single, it takes the 'picture' from the Album model it has a foreign key to rather than from it's own internal 'picture' object. My code is below, it renders the 'picture' for Singles perfectly, but cannot render the 'picture' object from the album and instead shows my {% else %} condition of a object not …