Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Macbook hang and start. Couldn't open http://127.0.0.1:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
I am a beginner on Django and Python. I am starting Django project by using coding in Visual Studio Code. It was going well until my Macbook Air hang and auto restart. All of sudden my http://127.0.0.1:8000/ backend could'nt open and shows error 404, Couldn't open http://127.0.0.1:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: enter image description here Can anyone able to give me a guidance with this? I have done python manage.py runserver in Visual Studio Code and it shows: System check identified no issues (0 silenced). September 29, 2022 - 08:00:11 Django version 4.1.1, using settings 'qrmenu_backend.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. However I am not able to open it. My code was running well until my Macbook restart so I am quite sure not the code problem. Also I have access into virtual environment as well. Is that I missed any command in terminal? from django.urls import path, include from core import views urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.authtoken')), path('api/places/', views.PlaceList.as_view()), path('api/places/<pk>', views.PlaceDetail.as_view()), path('api/categories/', views.CategoryList.as_view()), path('api/categories/<pk>', views.CategoryDetail.as_view()), path('api/menu_items/', views.MenuItemList.as_view()), path('api/menu_items/<pk>', views.MenuItemDetail.as_view()), ] -
How to set field name in django aggregate?
For example, My programs: [{"name": "html"}, {"name": "css"}, {"name": "css"}, {"name": "css"}] in database. models.py class Program: name = models.CharField(max_length=50) views.py class ProgramCountView(APIView): def get(self, request): query_list = [] programs = Program.objects.distinct().values_list("name", flat=True) for program in programs: query_list.append(Count("name", filter(Q(name=program))) result = Program.objects.aggregate(*query_list) return Response(result) But error has been: Complex aggregates require an alias. I want result like {"html": 1, "css": 3} -
Django select_related does not work properly
I am trying to make a JOIN request from my database via Django ORM. But select_related does not work properly. SQL request I'm trying to get: SELECT * FROM rel_observation_table inner join sp_fields on rel_observation_table.id_field = sp_fields.id My 1st table model class RelSubdivisionFields(models.Model): id_sp_subdivision = models.ForeignKey('SpSubdivision', models.DO_NOTHING, db_column='id_sp_subdivision', blank=True, null=True) id_field = models.ForeignKey('SpFields', models.DO_NOTHING, db_column='id_field') block = models.ForeignKey('SpFormBlocks', models.DO_NOTHING, db_column='block') order_index = models.IntegerField(blank=True, null=True) required = models.BooleanField() class Meta: managed = False db_table = 'rel_subdivision_fields' unique_together = (('id_sp_subdivision', 'id_field', 'block'),) My 2nd table model class SpFields(models.Model): id = models.IntegerField(primary_key=True, db_column='id') name = models.CharField(unique=True, max_length=100) field_type = models.CharField(max_length=20) rel_table = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'sp_fields' My QuerySet qs = RelObservationFields.objects.select_related('id_field') Result of QS execution >>> qs.values()[0] {'id_sp_observation_id': 80101, 'id_field_id': 1, 'block_id': 'with_error', 'order_index': 0, 'required': False, 'id': 90} As you can see, there are only columns from first table, I also need ones from the second. -
Getting data via Foreign Key
I am a fresh learner of django framework. I am trying to develop a learning portal, whereas every topic will have its own quiz. My models are as follows: class Quiz(models.Model): title = models.CharField(max_length=255) book_name = models.CharField(max_length=255) slug = models.SlugField(blank = True) topic = models.CharField(max_length=255) number_of_questions = models.IntegerField() class Meta: verbose_name_plural = 'Quizes' def __str__(self): return self.title my question model is as follows: class Quest(models.Model): quiz = models.ForeignKey(Quiz, on_delete= models.CASCADE) question_text = models.CharField(max_length=500) option_1 = models.CharField(max_length=250) option_2 = models.CharField(max_length=250) corr_ans = models.CharField(max_length=250) def __str__(self): return self.question_text class Meta: verbose_name_plural = 'Questions' my view is as under: def questions(request, url): questions = Quiz.quest_set.filter(slug = url) return render(request, 'quiz/questions.html', {'questions': questions}) Every quiz has multiple quest (questions). I want to call the questions by using quiz slug. Django is showing me an error "'ReverseManyToOneDescriptor' object has no attribute 'filter'". I tried and search a lot, however, could not figured it out, how to throw the questions via using quiz slug i.e. reverse look up. I have also referred the following stackoverflow's link [https://stackoverflow.com/questions/15306897/django-reverse-lookup-of-foreign-keys][1] What would be the best way to get questions related to a particular quiz and view it on the page, as every book will have multiple quizzes, and to … -
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