Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Recover Project Lost with Git using netbeans, github
I was trying to save my project to my private github repository. But, Now the files are neither locally nor in the repository. ==[IDE]== Jul 4, 2020 1:28:35 AM Initializing ... Initializing repository Creating git /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/.git directory git init /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull ==[IDE]== Jul 4, 2020 1:28:35 AM Initializing ... finished. ==[IDE]== Jul 4, 2020 1:30:00 AM Committing... Git Commit ---------- git add /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/DelFile.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/old/Text_macOS_Windows.old /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/DelWord.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Folder.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/DelSearch.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/AddSearch.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Selected.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/TabHeader.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/Text_All_OS.txt /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/lafcolorfont/MethodStringDimension.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/DecoratedTextMutableTreeNode.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RecursiveFolderAndFiles.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/Text_CentOS_Windows.txt /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/Text_macOS_Windows.txt /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RulerPanel.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/SearchDTO.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/BasicTabbedPaneUIColored.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/lafcolorfont/JFontChooser.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Lens.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/TreeCellRendererTextPane.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/Exceptions.txt /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/old/Text_CentOS_Windows.old /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/AddWord.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/DelFolder.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/old/Text_CentOS_macOS.old /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RulerComboBoxEditor.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Remove.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Unselected.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/Searcher.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/lafcolorfont/MethodGUI.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/DisabledExclude.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/AddFolder.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/DecoratedText.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/OneSearch.form /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/DisabledInclude.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Exclude.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/MainClass.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/AddWord2.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/lafcolorfont/MainMenu.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RulerComboBoxModel.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RulerData.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Include.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/AddFile.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/AddFile2.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RulerComboBox.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/PanelHorzSeparator.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RulerComboBoxRenderer.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/OneSearch.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Stop2.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RecursiveFolderAndFiles.form /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/Text_CentOS_macOS.txt /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/old/Text_All_OS.old /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Add.png git commit -m First Commit /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/DelFile.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/old/Text_macOS_Windows.old /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/DelWord.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Folder.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/DelSearch.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/AddSearch.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Selected.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/TabHeader.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/Text_All_OS.txt /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/lafcolorfont/MethodStringDimension.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/DecoratedTextMutableTreeNode.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RecursiveFolderAndFiles.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/Text_CentOS_Windows.txt /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/Text_macOS_Windows.txt /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RulerPanel.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/SearchDTO.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/BasicTabbedPaneUIColored.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/lafcolorfont/JFontChooser.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Lens.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/TreeCellRendererTextPane.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/Exceptions.txt /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/old/Text_CentOS_Windows.old /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/AddWord.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/DelFolder.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/old/Text_CentOS_macOS.old /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RulerComboBoxEditor.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Remove.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Unselected.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/Searcher.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/lafcolorfont/MethodGUI.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/DisabledExclude.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/AddFolder.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/DecoratedText.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/OneSearch.form /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/DisabledInclude.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Exclude.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/MainClass.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/AddWord2.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/lafcolorfont/MainMenu.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RulerComboBoxModel.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RulerData.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Include.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/AddFile.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/AddFile2.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RulerComboBox.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/PanelHorzSeparator.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RulerComboBoxRenderer.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/OneSearch.java /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Stop2.png /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/RecursiveFolderAndFiles.form /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/Text_CentOS_macOS.txt /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/TextTests/old/Text_All_OS.old /Users/joseluisbz/Documentos/Java/FlexibleFileFinderFull/src/org/bz/filefinder/usedPictures/Add.png Commit Log revision : 1d21d90944e6433303c909be7fe87d07145e0bea author : Jose Luis Bernal Zambrano <joseluisbz@gmail.com> date : Jul 4, 2020 1:30:03 AM summary : First Commit INFO: End of Commit ==[IDE]== … -
How to deploy a django project in my local server?
How to deploy a django project in my local server ? I have downlaod a django project code,now i want to run the project in my local computer i already install python and django but i dont not the step can any one hep me on that. -
Django Error Connect Aborted When fetching data from postgres
How to Solve This Connection Aboarted [10053] Error -
Placing django_markdown2 in PYTHONPATH
I am going over the documentation for using django-markdown2 in Project1, and I don't know what is the best way to: -'Place django_markdown2 somewhere in your PYTHONPATH.' https://github.com/svetlyak40wt/django-markdown2 I am using forms to pass the variable 'content' to read the .md modules. class CreatePageForm(forms.Form): title = forms.CharField(max_length=50, widget=forms.TextInput( attrs={"class": 'content', "placeholder": "Type title", })) content = forms.CharField(widget=forms.Textarea( attrs={"class": 'content', "placeholder": "Type content", 'rows': 20, 'cols': 80})) this is what I have in the template: {% extends "encyclopedia/layout.html" %} {% load md2 %} {% block title %} {{ title }} {% endblock %} {% block body %} <div class="content-markdown"> {{ content|markdown }} </div> <br> <a href="{% url 'edit' title %}">Edit</a> <br> {% endblock %} I need to know how I can place django_markdown2 in my PYTHONPATH and make it work with the forms I created, if it is possible how it should be done -
How to get parameters from a login_required route in flask?
I have been trying to understand an error for a while now, and have come to the conclusion that @login_required is not allowing me to pull values from the route in my function @main.route('/follow/<user_id>') @login_required def follow_user(user_id): referrer = request.headers.get("Referer") target_user = User.query.get(user_id) When I pass the user_id parameter to the query it returns None( it returns the correct value if I manually enter a user id in there) and I need a way to get a reference to the user being followed. Any help would be greatly appreciated. -
Django - How to add context data to 'for loop' in ListView
I have a ListView where I overwrite get_context_data as follows: class SongList(generic.ListView): model = models.Song template_name = 'videos/song_list.html' context_object_name = 'song_list' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) from pymystem3 import Mystem m = Mystem() k = [] t = [] song_dict = {'title': t, 'known': k} for song in context['song_list']: user_flash = Flashcard.objects.filter(owner=self.request.user).values_list('question', flat=True) song = models.Song.objects.get(title=song) t.append(song.title) lyrics_list = models.Song.objects.get(title=song).lyrics_as_list() user_flash_ = [item.replace('\n', ' ') for item in m.lemmatize(" ".join(user_flash))] lyrics_list_ = [item.replace('\n', ' ') for item in m.lemmatize(" ".join(lyrics_list))] user_word = list(set(user_flash_) & set(lyrics_list_)) stat = ((len(user_word))/(len(set(lyrics_list_))))*100 k.append(stat) context['percent_known'] = song_dict['known'] context['song_dict'] = list(zip(song_dict['title'],song_dict['known'])) return context Now in my html I want to show the artist, the song title, and the percent_known together. To do it separately is easy: {% for song in song_list %} <div class="card-songs text-center"> <div class="card-body"> <h5 class="card-title">{{song.artist}}</h5> <p class="card-text">{{song.title}}</p> <a href="{% url 'videos:song-detail' song.pk %}" class="btn btn-primary">Watch</a> </div> </div> And: {% for song in song_dict %} {{song.0}} -- {{song.1}} {% endfor %} But I want it all together for every song, and I'm at a loss as to how to do it, since percent_known is not a field in my Song model. Any advice? -
Django render api form into html and post to create new item
views.py class CreateProduct(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'product-create.html' def get(self, request): serializer = item_serializer return Response({'serializer': serializer}) def post(self, request): if request.method == 'POST': # print(request.data) serializer = item_serializer(data=request.data) if serializer.is_valid(): return Response({'serializer': serializer}) else: print('this post request is failure') product-create.html % extends "layouts/base.html" %} {% load rest_framework %} {% block title %} Create Item {% endblock %} <!-- Specific CSS goes HERE --> {% block stylesheets %}{% endblock stylesheets %} {% block content %} <div class="pcoded-content"> <div class="pcoded-inner-content"> <div class="main-body"> <div class="page-wrapper"> <h1>Create Products</h1> <form action="" method="POST"> {% csrf_token %} {% render_form serializer %} <input type="submit" value="Save"> </form> </div> </div> </div> </div> {% endblock %} <!-- Specific Page JS goes HERE --> {% block javascripts %}{% endblock javascripts %} want to render the api serializer into html, i did it by getting the visualize form, but the post method didt work and i get this error. expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` how do i get the post method to work and get the create the API ? -
Cannot router Django with Pyinstaller
I have some issue when deploy Django project with Pyinstaller. this is my url.py file from django.contrib import admin from django.conf.urls import url, include from django.urls import path from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token from . import settings from django.conf.urls.static import static urlpatterns = [ path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('admin/', admin.site.urls), url(r'', include('cip.urls')), url(r'^jwt-auth/', obtain_jwt_token), path(r'api-token-auth/', obtain_jwt_token), path(r'api-token-refresh/', refresh_jwt_token), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) After I run pyinstaller, run the server. I get a message that cannot read the router declaration. ./dist/testsite/testsite runserver 0.0.0.0:8900 Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "threading.py", line 926, in _bootstrap_inner File "threading.py", line 870, in run File "site-packages/django/utils/autoreload.py", line 54, in wrapper File "/home/ubuntu/ai/CheckInPlatform/test-pyinstaller/dist/testsite/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "site-packages/django/core/management/base.py", line 390, in check File "site-packages/django/core/management/base.py", line 377, in _run_checks File "site-packages/django/core/checks/registry.py", line 72, in run_checks File "site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique File "site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces File "site-packages/django/utils/functional.py", line 80, in __get__ File "site-packages/django/urls/resolvers.py", line 584, in url_patterns File "site-packages/django/utils/functional.py", line 80, in __get__ File "site-packages/django/urls/resolvers.py", line 577, in urlconf_module File "importlib/__init__.py", line 127, in import_module File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", … -
Django database filter in front end
I have a query like following that I would like to implement it in front end: MembershipPayment.objects.filter(group__name=tg.group_name).are_valid().count() I know that I can pass this from view to front-end html, but the problem is that in the front end I have a query-set containing many "group"s . so I need to run the similar query for each of those "group"s. I need something along these lines [this code of course wont work] in front: {% for rec in groups %} <tr> <td>{{ MembershipPayment.objects.filter(group__name=tg.group_name).are_valid.count }}</td> </tr> {% endfor %} So I was wondering how can I achieve this without changing my model structure (if possible). -
Django form password TypeError: __init__() got an unexpected keyword argument 'widget'
I have this code in my models.py from django import forms class user_Account(models.Model): password = models.CharField(widget=forms.PasswordInput(), verbose_name="Password", max_length=500, null=True, blank=True) this is my forms.py from django import forms from Account.models import user_Account class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = user_Account why i am getting this error? TypeError: init() got an unexpected keyword argument 'widget' did i miss something? -
I was trying to do django multifileselect function in template but I am having problem to do it
I am trying to add multiselectfield in django template and I have done like the below code but it is having problem in template. Except template in django admin it is working perfectly but I want it in custom template field. #models.py from multiselectfield import MultiSelectField class Amenities(models.Model): Amenities_Choices =( ('Free Wifi','Free Wifi'), ('Attach Bathroom', 'Attach Bathroom'), ('Shared Bathroom', 'Shared Bathroom'), ('Free Laundry Service', 'Free Laundry Service',), ('24/7 water facility', '24/7 water facility'), ('Geyser', 'Geyser'), ('Private TV', 'Private TV'), ) hostel = models.ForeignKey(AddHostel, on_delete=models.CASCADE) feature = MultiSelectField(choices=Amenities_Choices) def __str__(self): return self.hostel.location in views.py I have added like this def amenities(request): if request.method == "POST": hostel = request.POST['hostel'] feature = request.POST['feature'] amen = Amenities(hostel_id=hostel, feature=feature) amen.save() hostels = AddHostel.objects.all() return render(request,'staff/amenities.html',{'hostels':hostels}) <div class="col-lg-12"> <form method="post"> {% csrf_token %} <div class="row"> <div class="form-group col-md-6 col-sm-12"> <label for="hostel">Hostel:</label> <select class="form-control form-search-ch" id="hostel" name="hostel"> {% for h in hostels %} <option value="{{ h.id }}">{{ h.hostel_name }}</option> {% endfor %} </select> {# <input type="text" class="form-control form-grp-lbl" id="hostel" name="hostel"#} {# required>#} </div> <div class="form-group col-md-6 col-sm-12"> <!--in this section checkbox is not showing--> {% for value, text in form.amenities.field.choices %} <div class="ui slider checkbox"> <input id="{{ forloop.counter0 }}" name="{{ form.feature }}" type="checkbox" value="{{ feature }}"{% if … -
Using A Custom Form Template Causes Form Items To Break Page Layout
I'm displaying a table containing form data among other data which has come from the DB but is not part of the form. {% for book in user.books.all %} <tr> <td>{{ book.name }}</td> <td>{{ book.author }}</td> # display related checkbox {% for item in form %} {% if item.instance.book.id == book.id %} {{ item }} {% endif %} {% endfor %} The problem is the checkbox is surrounded by row tags, ruining the layout of my table. I need to customize how the checkboxes are displayed. I've tried several things, the closest I came was using a crispy forms custom layout. # custom layout for checkbox # this links to a file with a custom layout class CustomCheckbox(Field): template = '../custom_checkbox.html' class BookDataForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(BookDataForm, self).__init__(*args, **kwargs) self.helper = FormHelper() # remove labels self.fields['read'].label = '' # add custom layout self.helper.layout = Layout( CustomCheckbox('read'), ) This uses the custom layout I've specified, but it outputs all the checkboxes above the table they're supposed to be in (above {% for book in user.books.all %}). How can I customize these checkboxes/form fields (or at least prevent each from having <row> tags which mess up my table layout)? Thank you. -
Django crispy forms 'form-inline' doesn't works as expected
I have followed the crispy forms docs to create a simple inline form using bootstarp4. But it seems the form is not becoming a "inline" but a "horizontal". Here is the code snippet that I have so far along with the screenshot of the rendered web view, # models.py from django.db import models class InlineTestModel(models.Model): name = models.CharField(max_length=20) age = models.IntegerField() email = models.EmailField() # form_helper.py from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit class FormHelperBase(FormHelper): form_inputs = [] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.set_inputs() def set_inputs(self): for form_input in self.form_inputs: self.add_input(form_input) class TestInlineFormHelper(FormHelperBase): form_class = 'form-inline' field_template = 'bootstrap4/layout/inline_field.html' form_inputs = [ Submit('Save', 'Save', css_class='button white') ] # forms.py from django import forms class TestInlineForm(forms.ModelForm): helper = TestInlineFormHelper() class Meta: model = InlineTestModel fields = '__all__' # views.py from django.views import generic from django.urls import reverse class TestInlineAddView(generic.CreateView): model = InlineTestModel form_class = TestInlineForm template_name = 'app_name/test_inline_add.html' def get_success_url(self): return reverse('app_name:success_url') Rendered web view -
Render a dictionary in django templates
I have a dataframe that I am trying to render in a django template. I first turned my dataframe into a dictionary using post = df.to_dict() and passed it into my template with {'posts': post}. Now I am trying to render it in a template with the following code. {% for post in posts %} <tr> <td>{{ post.var1 }}</td> <td>{{ post.var2 }}</td> <td>{{ post.var3 }}</td> </tr> {% endfor %} The right number of rows are being rendered but the data is not being filled in to the individual cells. -
I am getting an error when itterating a dictionnary object in django
When I run the code bellow, I am getting an error:'dict' object has no attribute 'id_etat_v' date = [] nbre =[] etat = [] queryset = VehicEtatN.objects.values('id_etat_v','date_etat_v').annotate(count_v = Count('id_vehicule')) for item in queryset: etat.append(item.id_etat_v) date.append(item.date_etat_v) nbre.append(item.count_v) Here is the model.py: class VehicEtatN(models.Model): id_vehicule = models.ForeignKey('Vehicule', models.DO_NOTHING, db_column='id_vehicule', blank=True, null=True) id_etat_v = models.ForeignKey(EtatVehicule, models.DO_NOTHING, db_column='id_etat_v', blank=True, null=True) date_etat_v = models.DateField() -
Trying to show model data on web page by using ListView. Its not working
I created the model post and I want to show all the posts on Web Page using Class-based views but It's not working. the URL is opening but the web page is not showing anything( stuff that is on homepage.html and on _post.html but navbar is there which is coming from _inject.html). The problem is in coding in the template. Post Model- class Post(models.Model): auther = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) heading = models.CharField(max_length=400) message = models.TextField() message_html = models.TextField(editable=False) def __str__(self): return self.message def save(self,*args,**kwargs): self.message_html = misaka.html(self.message) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:single',kwargs={'username':self.user.username,'pk':self.pk}) class Meta: ordering = ['-created_at'] unique_together = ['auther','message'] Post view- class ListPosts(generic.ListView): model = models.Post template_name = "homepage.html" homepage.html {% extends "_inject.html" %} {% block content %} <div class="col-md-8"> {% if post.count == 0 %} <h2>No posts in this group yet!</h2> {% else %} <ul> {% for p in Post.all %} <h1>p.message</h1> <li> {% include "_post.html" %} </li> {% endfor %} </ul> {% endif %} </div> {% endblock %} _post.html- <div class="media"> <h3 class="mr-5"><a href="{% url 'posts:for_user' username=post.user.username %}">@{{ post.user.username }}</a></h3> <div class="media-body"> <strong>{{ p.user.username }}</strong> <h5>{{ p.message_html|safe }}</h5> <time class="time"><a href="{% url 'posts:single' username=post.user.username pk=post.pk %}">{{ p.created_at }}</a></time> <div class="media-footer"> {% if user.is_authenticated and post.user … -
Reset password link on Django website not working in production
I have a django website. It has sign up and login functionality for users. It's currently hosted on pythonanywhere. I am using the gmail smtp server to send mails from the contact form and for reset password. But the reset link sent in the email is not working. When I'm running the localhost, the link works but not when hosted on pythonanywhere. What could be wrong? Here is my urls.py file's code: enter image description here -
Is there a way I can install pillow on my windows machine?
I tried installing the pillow library but I got this message (venv) C:\Users\Timo\PycharmProjects\jumia>pip install pillow Collecting pillow Using cached https://files.pythonhosted.org/packages/3e/02/b09732ca4b14405ff159c470a612979acfc6e8645dc32f83ea0129709f7a/Pillow-7.2.0.tar.gz Installing collected packages: pillow Running setup.py install for pillow ... error Complete output from command C:\Users\Timo\PycharmProjects\jumia\venv\Scripts\python.exe -u -c "import setuptools, tokenize;file='C:\Users\Timo\AppData\Local\Temp\pip-install-gr4big0c\pillow\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\Timo\AppData\Local\Temp\pip-record-yl39rrsa\install-record.txt --single-version-externally-managed --compile --install-headers C:\Users\Timo\PycharmProjects\jumia\venv\include\site\python3.8\pillow: running install running build running build_py creating build creating build\lib.win-amd64-3.8 creating build\lib.win-amd64-3.8\PIL copying src\PIL\BdfFontFile.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\BlpImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\BmpImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\BufrStubImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\ContainerIO.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\CurImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\DcxImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\DdsImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\EpsImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\ExifTags.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\features.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\FitsStubImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\FliImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\FontFile.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\FpxImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\FtexImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\GbrImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\GdImageFile.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\GifImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\GimpGradientFile.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\GimpPaletteFile.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\GribStubImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\Hdf5StubImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\IcnsImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\IcoImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\Image.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\ImageChops.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\ImageCms.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\ImageColor.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\ImageDraw.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\ImageDraw2.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\ImageEnhance.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\ImageFile.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\ImageFilter.py -> … -
Suggestion about a quality indicator - deliveries Rate - django app for statistics
hope you are doing well ! I want to do a " quality indicator ". I build a django web app where the admin can import data about deliveries, example like in my class here: class Evenement(models.Model): EVENEMENT_CHOICES = ( ("déposé","déposé"), ("reçu","reçu"), ("expédié","expédié"), ("affecté","affecté"), ("livré","livré"), ("echec de livraison","echec de livraison"), ) mail_item_fid = models.ForeignKey(mail_item,on_delete=models.CASCADE, related_name='mail_item_fid_evenement') from_office = models.ForeignKey(Office,on_delete=models.CASCADE, related_name='office_Evt_evenement') date_Evt = models.DateTimeField() status = models.CharField(max_length=50,choices=EVENEMENT_CHOICES) agent_delivery_cd = models.ForeignKey(Delivery_Agent,on_delete=models.CASCADE,blank=True, null=True ,related_name='agent_evenement') def __str__(self): return '{}, {}, {}, {} '.format(self.mail_item_fid,self.from_office,self.date_Evt,self.status) this is an example if the admin imported data in Evenement: I want to count whether the mail-items delivered in the same day or the next day. like 'the mails (status == affecté) assigned to agents in a X day are (status == livré) delivered in the same day ' in here by doing this "indicator" I can know the productivity of agents toward the mails, I hope you could understand what I meant I would like your suggestions because I don't know what do to acheive that. -
TypeError: 'unicode_results' is an invalid keyword argument for this function
I created changed my database in django from sqlite3 to mysql. It worked fine untill i tried to download some packeges for making UML diagrams. After i read a lot of questions related to this problem and i tried to uninstall mysql-client and mysql-server, purge, autoclean autoremove but the error was still there. I also read an anwear that told that might be a problem with Django. I created a new virtual enviroment, i've installed everything again, i deleted all migrations and now i get this error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/anamaria/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/anamaria/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/anamaria/.local/lib/python3.6/site-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/home/anamaria/.local/lib/python3.6/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/home/anamaria/.local/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/anamaria/.local/lib/python3.6/site-packages/django/core/checks/model_checks.py", line 34, in check_all_models errors.extend(model.check(**kwargs)) File "/home/anamaria/.local/lib/python3.6/site-packages/django/db/models/base.py", line 1275, in check *cls._check_constraints(), File "/home/anamaria/.local/lib/python3.6/site-packages/django/db/models/base.py", line 1843, in _check_constraints connection.features.supports_table_check_constraints or File "/home/anamaria/.local/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/anamaria/.local/lib/python3.6/site-packages/django/db/backends/mysql/features.py", line 93, in supports_column_check_constraints if self.connection.mysql_is_mariadb: File "/home/anamaria/.local/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] … -
Custom tag with both parse_until and simple. Error "Unclosed tag on line 10 Looking for one of: endblock"
I want to make a tag that: if there is an endblcok endsome, it would act as parse_untill — grab everything that is between start and end, and work with it, if no endsome — other logic. For this purpose during compilation I run parser, and if it does not find endblock, it raises exception: try: nodelist = parser.parse(('endsome',)) parser.delete_first_token() return SomeNode(nodelist) except TemplateSyntaxError as e: if 'endsome' in str(e): return SomeNode() In a template I have: {% some %} Everything goes OK: it parses, does not find endblock, goes the exception way and even calls __init__ of SomeNode() But after this — it raises exception: Unclosed tag on line 10: 'some'. Looking for one of: endblock. Exception is raised on 482nd line: https://github.com/django/django/blob/stable/3.0.x/django/template/base.py#L482 Is there a way to stop it searching for the endblock? Is it even possible to make such tag? What am I missing? -
How do I save a form when one class depends on another?
I'm trying to write a simple review page where a person (Person A) can leave a review about another person (Person B). Person B can then reply to it. It's similar to reviewing products on Amazon and the seller can respond back. I have created two tables where one relies on the other. The content is saved in one table, but the reference to it is in another table. How would I go about saving to the database, or should I have designed my models differently? models.py class ReviewContent(BaseModel): content = models.TextField() rating = models.IntegerField(null=True) class Review(BaseModel): by_user = models.ForeignKey(User, on_delete=models.CASCADE) to_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_user') review_content = models.ForeignKey(ReviewContent, on_delete=models.CASCADE, related_name='review_content') reply_content = models.ForeignKey(ReviewContent, on_delete=models.CASCADE) forms.py class UserReputationCreate(forms.Form): OPTIONS = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5') ) review = forms.CharField( widget=forms.Textarea( attrs={'rows': '5', 'placeholder': 'Please leave a review. Remember, all reviews are public.'}), label=False) rating = forms.CharField(label='Please leave a rating.', widget=forms.Select(choices=OPTIONS)) views.py (here is where I'm stuck) def profile_create_review(request, username): form = UserReputationCreate(request.POST or None) to_user_review = User.objects.get(username=username).pk if request.method == 'POST': if form.is_valid(): by_user_review = request.user.id content = form.cleaned_data['review'] p = Review(to_user_id=to_user_review, by_user_id=by_user_review) p.save() return render(request, 'users/user-reputation-home.html') else: form = UserReputationCreate() context = { … -
Page loads an image that doesn't exist in my folder
I am working on a web app. I found a free template to use for my home page and I copied the navbar from the HTML: <div class="container"> <div class="header__inner"> <div class="header__logo"><a href=""><img src="{% static 'home/img/logo.png' %}" alt="Logo" /></a></div> <div class="header__menu"> <!-- onepage-nav --> <nav class="onepage-nav"> <!-- onepage-menu --> <ul class="onepage-menu"> <li class="current-menu-item"><a href="#">Home</a> </li> <li><a href="#">Discover</a> </li> <li><a href="#">Events</a> </li> <li><a href="">About</a> </ul><!-- onepage-menu --> <div class="navbar-toggle"><span></span><span></span><span></span></div> </nav><!-- End / onepage-nav --> </div> </div> </div> I am trying to change the image. I have another project that uses the free template in the same folder with the project I'm working on, but my current project doesn't even have any folders in static directory. So there's no images, CSS, JS or styling at all in my current project. I can't find what's the problem with it. -
Django ListView calculated value only returns one value
I have a Song model with a ListView and a DetailView. On the ListView I want to display how many words a user knows for every song (based on a Flashcard model). Originally my code was as follows: class SongList(generic.ListView): model = models.Song template_name = 'videos/song_list.html' context_object_name = 'song_list' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) from pymystem3 import Mystem m = Mystem() for song in context['song_list']: user_flash = Flashcard.objects.filter(owner=self.request.user).values_list('question', flat=True) lyrics_list = models.Song.objects.get().lyrics_as_list() user_flash_ = [item.replace('\n', ' ') for item in m.lemmatize(" ".join(user_flash))] lyrics_list_ = [item.replace('\n', ' ') for item in m.lemmatize(" ".join(lyrics_list))] user_word = list(set(user_flash_) & set(lyrics_list_)) percent_known = ((len(user_word))/(len(set(lyrics_list_))))*100 context['percent_known'] = percent_known return context And it worked. But there was only one song. When I added another song, I got a MultipleObjectsReturned exception. So to fix that I changed my code to: lyrics_list = models.Song.objects.get(title=song).lyrics_as_list() Now the error is gone, but I get only one value for percent_known, instead of two. So I changed my code as follows: for song in context['song_list']: n = [] song_dict = {'title': song, 'known': n} user_flash = Flashcard.objects.filter(owner=self.request.user).values_list('question', flat=True) lyrics_list = models.Song.objects.get(title=song).lyrics_as_list() user_flash_ = [item.replace('\n', ' ') for item in m.lemmatize(" ".join(user_flash))] lyrics_list_ = [item.replace('\n', ' ') for item in m.lemmatize(" ".join(lyrics_list))] … -
How to get the sum of Items model from a Many Order Model?
I am trying to get the total no. of a sold item after payment is made. When the order is paid ordered = models.BooleanField(default=False) become True I wrote the code which got me a little close to what I want but I am getting the total no. of orders with the item not the total quantity of the order. I have also tried to add the quantity in the ordered item but I get a 'Item' object has no attribute 'orderitem' so I commented it for your reference Here is the item model class Item(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title @property def count_sold(self): return self.orderitem_set.filter(ordered=True).count() # return self.OrderItem.quantity_set.filter(ordered=True).count() Here is the OrderItem model: class OrderItem(models.Model): ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) Here is the order model class Order(models.Model): items = models.ManyToManyField(OrderItem) Here is the template <tr> td>No. of Sold:</td> <td>{{ item.count_sold }}</td> </tr>