Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to display checkbox multi-select in django
if I select all checkbox then my checkbox display only one thing i want display multi select checkbox in django. what is problem in my code? in html <form action="" method="GET"> <label style="color: gray;" >&nbsp; 확장자 -</label> {% for extention in file_extention %} {% if extention.name == extention_name %} <input type="checkbox" name="extention_name" value="{{ extention.name }}" checked>{{ extention.name }} {% else %} <input type="checkbox" name="extention_name" value="{{ extention.name }}"> {{ extention.name }} {% endif %} {% endfor %} </form> in views.py if request.method == 'GET': png = {'name' : '.png'} jpg = {'name' : '.jpg'} gif = {'name' : '.gif'} file_extention = [png, jpg, gif] context = {} context['file_extention'] = file_extention extention_name = request.GET.get('extention_name',None) context['extention_name'] = extention_name return render(request, 'home/index.html',context)``` -
django model order the queryset with booleanfield field True/False
i have tow model as the following , first one is a user profile, which have a FK to User model : class Profile(models.Model): PRF_user = models.OneToOneField(User, related_name='related_PRF_user', on_delete=models.CASCADE) PRF_Priority_Support = models.BooleanField(default=False) and the second is ticket model which have a FK to User model : class ticket(models.Model): ticket_status_options = [ ('open', 'open'), ('wait_customer_reply', 'wait_customer_reply'), ('replied_by_staff', 'replied_by_staff'), ('replied_by_customer', 'replied_by_customer'), ('solved', 'solved'), ] TKT_USER = models.ForeignKey(User, related_name='TKT_USER', on_delete=models.CASCADE) TKT_DEB = models.ForeignKey('Site_departments', related_name='related_ticket_department', on_delete=models.CASCADE) TKT_SUB = models.CharField(max_length=50, db_index=True, verbose_name="ticket subject") TKT_BOD = models.TextField(verbose_name="ticket body") TKT_image_attachment = models.ImageField(upload_to='TKT_img_attachment', blank=True, null=True , default=None) TKT_CREATED_DATE = models.DateTimeField(auto_now_add=True) TKT_UPDATED_DATE = models.DateTimeField(auto_now=True) i want to sort the tickets based on user profile Priority_Support , if the user profile PRF_Priority_Support is True , i want to sort it first , if False sort it normal . kindly help -
CheckConstraint throwing a Pylint 'undefined variable F' error
I'm not sure if I need to import a particular module, I've had a look round and can't seem to find one? Pylint is showing an "Undefined Variable 'F' " error on both of the CheckConstraints. from django.contrib.auth.models import AbstractUser from django.db.models.fields import DateTimeField from django.db.models.query_utils import Q from django.utils import timezone from django.db import models class UserProfile(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="profileUser") user_following = models.ForeignKey("User", on_delete=models.CASCADE, related_name="following") user_follower = models.ForeignKey("User", on_delete=models.CASCADE, related_name="followers") class Meta: constraints = [ models.CheckConstraint(check=~Q(user=F('user_following', 'user_follower')), name="user_cannot_follow_themselves"), models.CheckConstraint(check=~Q(user_following=F('user_follower')), name="cannot_follow_and_be_following") ] -
Relative paths in django-meta module and twitter card config
I've tried to follow instructions of the django-meta module, everything works fine in absolute paths, using the view config in my project. from meta.views import MetadataMixin class MyView(MetadataMixin, View): title = 'Some page' description = 'This is an awesome page' image = 'img/some_page_thumb.gif' url = 'some/page/' ... and the configs in settings: META_USE_OG_PROPERTIES = True META_USE_TWITTER_PROPERTIES = True META_SITE_TYPE META_SITE_PROTOCOL = 'https' ... My problem is that I can't render in views the dynamic paths for image of my blog, etc... and also can't configure the twitter card ("twitter_type"). Any ideas would be appreciated -
Django webpage only shows a 0
When ever I start the the server it does start up the server. But when I open the page it just shows a 0 instead of the normal Django landing page. Ive tried opening the login page they provide but it still just shows a 0 Version: 2.0.2 -
Detect dead code which never gets executed
I am searching for code coverage, but not for tests, but for production code. Which lines of my code get executed often, and which lines gets executed hardly or never (in production)? Of course this measuring must not slow down the production system noticably. Is there a way to do this? To simplify this, I want to use this for our Python (Django) code first. How could get a code coverage from production code? -
Using AJAX with CBV in Django for posting without refreshing
I wanna upgrade my creating post functionality just to make new posts without refreshing the page. Example, which I found, uses function views as example, but I use class-based views in my own project. So i faced with problem of adapting example codes to my code. Currently by submitting the form new for new post appears but it doesn't save data to DB and in my .js file i try to prepend() some code to this div and call some variables from json, but all that i get - "undefined" in each call. As I understand the most of mistakes exist in views.py, but can't analize correctly. my .html template: {% block post_content %} <div class="post-form"> <form action="{% url 'posts:create' %}" method="POST" enctype="multipart/form-data" id='post-form'> {% csrf_token %} <textarea id='post-text' type="text" name='post_message' rows="8"></textarea><br> <input id='post-image' type="file" name="post_image" accept="image/*"><br> <input id='post-submit' type="submit" value="Post"> </form> </div> {% endblock %} {% block post_post %} <div class="post-container" > <div class="current-post-container" id='talk'> {% for post in post_list %} {% include 'posts/_post.html'%} {% endfor %} </div> </div> <script src='https://code.jquery.com/jquery-3.5.1.min.js'></script> <script src="https://d3js.org/d3.v6.min.js"></script> <script src="{% static 'simplesocial/js/main.js' %}"></script> {% endblock %} main.js: // Submit post on submit $('#post-form').on('submit', function(event){ event.preventDefault(); create_post(); }); // AJAX for posting function create_post() { … -
How to send normal JSON message from outside of consumer class in django channels
I am not using this Django channels for chat purpose, I am connecting the user through web socket via DRF AUTH token var ws = new WebSocket("ws://127.0.0.1:8008/ws/stream/<token>/") I want to achieve if the admin delete the User from backend then in mobile front end I will get the automatically response that user is deleted and then I will call the disconnect method, which will logout the user in front end for that below code I am using. But unable to send message from outside of consumer. Here below is my code:- class Consumer(AsyncJsonWebsocketConsumer): """ This chat consumer handles websocket connections for chat clients. It uses AsyncJsonWebsocketConsumer, which means all the handling functions must be async functions, and any sync work (like ORM access) has to be behind database_sync_to_async or sync_to_async. For more, read http://channels.readthedocs.io/en/latest/topics/consumers.html """ ##### WebSocket event handlers async def connect(self): """ Called when the websocket is handshaking as part of initial connection. """ # query_string = dict(self.scope).get('query_string') # keys = dict(parse.parse_qs(query_string.decode())) self.token_key = self.scope['url_route']['kwargs']['token'] try: if self.token_key: # access_token = keys.get('key') print(self.token_key) self.scope['user'] = await get_user(self.token_key) # self.chat_room = self.scope['url_route']['kwargs']['channel'] await self.accept() await self.send_json({'code':200, 'message': 'Connection establish successfully', 'error_message': '', 'data':{}}) except Exception as ex: print("Exception", ex) self.scope['user'] … -
When I do submit formset in Django why do it returns extra 5 fields in formset?
When I do submit formset in Django it returns extra 5 fields in formset. Suppose the initial queryset has 3 dictionary values. But when I do submit the formset its returns an extra 5 dictionary. Why? My form.py: class SbTitleForm(forms.Form): sb_title = forms.CharField(required=False) sb_permission = forms.BooleanField(required=False) SbTitleFormSet = formset_factory(SbTitleForm, extra=0) My view.py: def menuuser(request): sbtitle = SbTitle.objects.all().values() sbtitle_form = SbTitleFormSet(initial=sbtitle) if request.method == 'POST': sbtitle_form = SbTitleFormSet(request.POST, initial=sbtitle) if sbtitle_form.is_valid(): print(sbtitle_form.cleaned_data) context = { 'sbtitle_form':sbtitle_form, } return render(request, 'admins/user_role/user_permission.html', context) My HTML: {% extends 'base/base.html' %} {% load static %} {% block content %} <div class="card"> <form class="form-horizontal" action="" method="post"> {% csrf_token %} {{ sbtitle_form.management_form }} {{ sbitleelement_form.management_form }} <div id="DataTables_Table_2_wrapper" class="dataTables_wrapper no-footer"> <div class="datatable-scroll"> <table class="table table-bordered table-hover datatable-highlight dataTable no-footer" id="DataTables_Table_2" role="grid" aria-describedby="DataTables_Table_2_info"> <thead> <tr role="row" class="bg-teal-400"> <th class="sorting text-center h5" tabindex="0" aria-controls="DataTables_Table_2" rowspan="1" colspan="1" aria-label="Job Title: activate to sort column ascending">Sidebar Title</th> </tr> </thead> <tbody> {% for field in sbtitle_form %} <tr role="row" class="odd"> <td class="sorting_1 text-center"><h4>{{ field.sb_title.value }} {{ field.sb_permission }}<p class="text-danger">{{ field.errors.as_text }}</p></h4></td> {% endfor %} </tbody> </table> </div> <div class="card-footer"> <button class="btn btn-lg btn-primary" type="submit">Save</button> </div> </div> </form> </div> {% endblock %} when I try to print(sbtitle_form.cleaned_data) its return extra 5 field values like … -
Django inlineformset - jQuery add row
Hello I am trying to upload multiple images to the web via inlineformset. The inlineformset is working fine, but if I add feature to add more lines to upload the image, it upload only the original images and it does not upload the images which were added via jQuery Add row. I am not sure why it wont take it... Models.py class PostImage(models.Model): post = models.ForeignKey( Post, default=None, on_delete=models.CASCADE, related_name='postimages') class Post(models.Model): title = models.CharField(max_length=100) content = RichTextField(blank=True, null=True) Views.py class PostCreateView(LoginRequiredMixin, CreateView): form_class = CreatePostForm template_name = 'blog/post_form.html' def get_context_data(self, *args, **kwargs): context = super(PostCreateView, self).get_context_data(**kwargs) if self.request.POST: context['formset'] = PostImageFormSet(self.request.POST, self.request.FILES, instance=self.object) else: context['formset'] = PostImageFormSet() return context def form_valid(request): ---- template <form id="myForm" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form2 in formset.forms %} <div class="table"> <table class="no_error"> {{ form2|crispy }} </table> </div> <hr> {% endfor %} </fieldset> <div class="form-group"> <input class="btn btn btn-outline-primary btn-sm" type="button" value="Add Row" id="add_more"> <button class="btn btn-outline-info float-right" type="submit">Post</button> </div> </form> jQuery script: <script> $('#add_more').click(function() { cloneMore('div.table:last', 'service'); }); </script> <script> function cloneMore(selector, type) { var newElement = $(selector).clone(true); var total = $("#id_" + type + "-TOTAL_FORMS").val(); newElement.find(":input").each(function () { var name = $(this) .attr("name") .replace("-" + (total - … -
Django: How to add context variable as src to url?
I have a django model with a field for an external URL image_url = models.URLField(max_length=250) I want to then display an image associated with that image_url (say https://upload.wikimedia.org/wikipedia/commons/0/01/Pocky-Sticks.jpg) in an html img element like so <img src=image_url alt="didn't find image"> where i have passed image_url in as a context variable. When I try the naive method of just passing in a context variable <img src= "{{ model.image_url }}" alt="didn't find image"> I can never find the image. I have looked around and most answers for similar questions are related to loading an image from static (e.g. How to add django template variable in <img src>?. ) These haven't been helpful because I want to load an image from a path completely external to my app. Any ideas on how to pass in a context variable to src in this case? -
How does "template.Library()" and "get_related_name" work in django?
I'm working on a basic social media django project with the help of an udemy course. The following are the models i created: group : models.py register = template.Library() class Group(models.Model): name = models.CharField(max_length=255,unique=True) slug = models.SlugField(allow_unicode=True,unique=True) description = models.TextField(blank=True,default='') description_html = models.TextField(editable=False,default='',blank=True) members = models.ManyToManyField(User,through="GroupMember") class GroupMember(models.Model): group = models.ForeignKey(Group,related_name='memberships',on_delete=models.CASCADE) user = models.ForeignKey(User,related_name='user_groups',on_delete=models.CASCADE) post : models.py class Post(models.Model): user = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group,related_name='posts',null=True,blank=True) And the part that does not make any sense to me is the following: post_list.html {% for member_group in get_user_groups %} <a href="{% url 'groups:single' slug=member_group.group.slug %}">{{ member_group.group.name }}</a></li> {% endfor %} {% for other_group in get_other_groups %} <a href="{% url 'groups:single' slug=other_group.slug %}">{{ other_group.name }}</a></li> {% endfor %} What does "get_user_groups","get_other_groups" and "register = template.Library()" mean here and how are they related? Also what are they trying to achieve here? I'm clueless guys, help me out. -
'Command errored out with exit status 1' getting this error message while installing mysql client in python
(env) C:\Users\shreya kumar\Documents\django website\audit_website>pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.0.1.tar.gz (87 kB) Using legacy 'setup.py install' for mysqlclient, since package 'wheel' is not installed. Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\users\shreya kumar\documents\django website\env\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\shreya kumar\\AppData\\Local\\Temp\\pip-install-7l4hf6a3\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\shreya kumar\\AppData\\Local\\Temp\\pip-install-7l4hf6a3\\mysqlclient\\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\shreya kumar\AppData\Local\Temp\pip-record-npl_lx21\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\shreya kumar\documents\django website\env\include\site\python3.9\mysqlclient' cwd: C:\Users\shreya kumar\AppData\Local\Temp\pip-install-7l4hf6a3\mysqlclient\ Complete output (23 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.9 creating build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.9\MySQLdb creating build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.9\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\shreya kumar\documents\django website\env\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\shreya kumar\\AppData\\Local\\Temp\\pip-install-7l4hf6a3\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\shreya kumar\\AppData\\Local\\Temp\\pip-install-7l4hf6a3\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record … -
Form to appear in a popup panel
I have the following file setup: In forms.py class TableCheckInForm(forms.Form): guest_count = forms.IntegerField(min_value =0) In views.py: def table_checkin_view(request): if request.method == 'POST': form = TableCheckInForm(request.POST) if form.is_valid(): cd = form.cleaned_data else: form = TableCheckInForm() return render(request, 'table/table_checkin.html', {'form': form}) In the template table_view.html <script src="{% static 'js/table.js' %}"></script> ... <button class="button checkin_button" onclick="openForm()">Check In</button> ... In another template table_checkin.html {% load static %} <script src="{% static 'js/table.js' %}"></script> <div id="table_checkin_form"> <h1>Check-In</h1> <form class="form-container" method="post"> {{ form.as_p }} {% csrf_token %} <button type="submit" class="table_checkin" onclick="closeForm()">Check In</button> </form> </div> In static Javascript file table.js function openForm() { document.getElementById("table_checkin_form").style.display = "block"; } function closeForm() { document.getElementById("table_checkin_form").style.display = "none"; } In urls.py urlpatterns = [ ... path('', views.table_view, name='table_view'), path('1/checkin/', views.table_checkin_view, name='table_checkin_view'), ... ] I am trying to implement a popup panel that contains the form above, similar to this example from W3Schools here. Suppose I am currently on the template table_view.html. When I click the button checkin_button, I would like to have the form popup in a small panel that renders table_checkin.html. That means, in the background, I would like still see the template table_view.html. But the form in my case always appear in a completely new page. Putting aside the css effect, … -
django-summernote is not editable on Django admin page
Currently I am trying to implement django-summernote to my Django project. I could pip-install it, set up the urls.py, setting.py, admin.py but it is not working properly on admin page. If I go to the page, the information is displayed but it is not editable. Does anybody know how to fix this? Here is the info about package versions. Python 3.6.9 Django 2.1 django-summernote 0.8.11.6 And here is the screenshot image of the admin page. The data is displayed but the none of buttons for html customization is displayed, and this is not editable. I can not modify any sentence. I would really appreciate if somebody gave me any advice on this. Details package info↓ (This is result of "pip list") asgiref 3.2.10 beautifulsoup4 4.9.3 bs4 0.0.1 cachetools 4.1.1 certifi 2019.6.16 chardet 3.0.4 cssselect2 0.3.0 cycler 0.10.0 decorator 4.4.1 Django 2.1 django-bootstrap4 1.1.1 django-cleanup 4.0.0 django-filter 2.4.0 django-modelcluster 5.1 django-pandas 0.6.1 django-summernote 0.8.11.6 django-taggit 1.3.0 django-treebeard 4.3.1 djangorestframework 3.12.1 draftjs-exporter 2.1.7 et-xmlfile 1.0.1 google-api-core 1.22.2 google-api-python-client 1.11.0 google-auth 1.21.1 google-auth-httplib2 0.0.4 googleapis-common-protos 1.52.0 gspread 3.2.0 html5lib 1.1 httplib2 0.17.0 idna 2.8 importlib-metadata 1.7.0 jdcal 1.4.1 Jinja2 2.10.1 kiwisolver 1.2.0 l18n 2018.5 lxml 4.4.1 MarkupSafe 1.1.1 matplotlib 3.2.1 mplfinance 0.12.3a3 mysqlclient … -
Error: NoReverseMatch: Reverse for 'index' not found. 'index' is not a valid view function or pattern name
I'm developing websystem in Django, when I write a login function gives me this error: NoReverseMatch at /login/ Reverse for 'index' not found. 'index' is not a valid view function or pattern name. I checked the code a hundred times but there is something I'm missing and can't find the solution. I've been stuck on this for a while, can't seem to fix this error. The other parts from the website are working fine. views.py @login_required def index(request): return render(request, 'dashboard.html') def loginPage(request): form = AuthenticationForm() if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) if request.GET.get('next'): return redirect(request.GET.get('next')) else: return redirect('index') return render(request, 'login.html', {'form': form}) urls.py: urlpatterns = [ path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('', views.index, name="index"), ] login.html <body> <div class="container h-100"> <div class="d-flex justify-content-center h-100"> <div class="user_card"> <div class="d-flex justify-content-center"> <h3 id="form-title">Login</h3> </div> <div class="d-flex justify-content-center form_container"> <form method="POST" action=""> {% csrf_token %} {{form.as_p}} <div class="d-flex justify-content-center mt-3 login_container"> <input class="btn login_btn" type="submit" value="Login"> </div> </form> </div> </body> dashboard.html {% extends 'main.html' %} {% block content %} <br> <div class="row"> <div class="col-md-10"> <h5>Patients:</h5> <hr> <a class="btn btn-sm" href="">+ Create Patient</a> <div class="card card-body"> … -
why do I get a single field value in Django formset_factory?
when I checked formset_factory validation and get fields to value from formset it returns only one field value in formset. But I can not find any problem in my code. please help me to solve the problem. My form.py: class SbTitleForm(forms.Form): sb_title = forms.CharField(required=False) sb_permission = forms.BooleanField(required=False) SbTitleFormSet = formset_factory(SbTitleForm, extra=0) My view.py: def menuuser(request): sbtitle = SbTitle.objects.all().values() sbtitle_form = SbTitleFormSet(initial=sbtitle) if request.method == 'POST': sbtitle_form = SbTitleForm(request.POST, initial=sbtitle) if sbtitle_form.is_valid(): print(sbtitle_form.cleaned_data) context = { 'user_role':user_role, 'sbtitle_form':sbtitle_form, } return render(request, 'admins/user_role/user_permission.html', context) My HTML: {% extends 'base/base.html' %} {% load static %} {% block content %} <div class="card"> <form class="form-horizontal" action="" method="post"> {% csrf_token %} {{ sbtitle_form.management_form }} {{ sbitleelement_form.management_form }} <div id="DataTables_Table_2_wrapper" class="dataTables_wrapper no-footer"> <div class="datatable-scroll"> <table class="table table-bordered table-hover datatable-highlight dataTable no-footer" id="DataTables_Table_2" role="grid" aria-describedby="DataTables_Table_2_info"> <thead> <tr role="row" class="bg-teal-400"> <th class="sorting text-center h5" tabindex="0" aria-controls="DataTables_Table_2" rowspan="1" colspan="1" aria-label="Job Title: activate to sort column ascending">Sidebar Title</th> </tr> </thead> <tbody> {% for field in sbtitle_form %} <tr role="row" class="odd"> <td class="sorting_1 text-center"><h4>{{ field.sb_title.value }} {{ field.sb_permission }}<p class="text-danger">{{ field.errors.as_text }}</p></h4></td> {% endfor %} </tbody> </table> </div> <div class="card-footer"> <button class="btn btn-lg btn-primary" type="submit">Save</button> </div> </div> </form> </div> {% endblock %} when I try to print(sbtitle_form.cleaned_data) its return only one field … -
Django ORM: filtering over a primary key returning 2 objects
How is it possible for a ModelName.objects.get(id=XX) to return more than object when the model use the auto generated id field as the one and only primary key? TLDR; Exception: MultipleObjectsReturned: get() returned more than one XXX -- it returned 2! View: django.views.generic.DetailView Lookup field left unchanged and defaults to the auto created id field on model View class ProjectFilePreviewView(ProjectFilePermissionMixin, DetailView): template_name = "project_file_preview.html" model = ProjectFile def get(self, request, *args, **kwargs): pk = int(kwargs.get('pk')) redirect = False current = self.get_object() # <-- error here ... return super().get(request, *args, **kwargs) Model class XXX(models.Model): xx = models.ForeignKey( 'xxx', related_name='x', null=True, blank=True, verbose_name=_('xx')) xxx = models.ForeignKey(User, verbose_name=_('xx'), null=True, on_delete=models.SET_NULL) xxxx = models.FileField(_('xx'), max_length=512, upload_to=xx) xxxxx = models.ImageField(_('xx'), null=True, blank=True, max_length=512, upload_to='xx/') created_at = models.DateTimeField(_('created at'), auto_now_add=True) xxxxxx = models.DateTimeField(_('xx'), null=True, blank=True) Traceback MultipleObjectsReturned: get() returned more than one xxx -- it returned 2! File "django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "django/contrib/auth/mixins.py", line 56, in dispatch return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) File "django/views/generic/base.py", line 88, in dispatch return handler(request, … -
Get user from refresh token in Django Simple JWT's TokenRefreshView
I am trying to check if the user still exists when Refreshing the Token, returning the user's updated detail (if updated) upon refreshing a token. Is there anyway to retrieve the user's details from the refresh token? [request.user] is currently marked as AnonymousUser so I am unable to know who the refresh token belongs to. -
Passing date format to field in django
I working on an "edit profile page" where users can edit their information, but I am facing a problem displaying users birth date. Sidenote: The html input type="date" accepts date input in the format "YYYY-mm-dd" but displays it in the format "dd-mm-YYYY" The problem is that when I do this it displays the date fine: ... <input type="date" value={{ user.profile.birth_date|date:'Y-m-d }}> ... but when I do this it doesn't, and display nothing, it just says dd/mm/yyyy <form method="POST"> {% csrf_token %} {% for field in form %} {{ field.label_tag }} {{ field }} {% endfor %} </form> How can I pass the field the value of the birth date in the format "YYYY-mm-dd" -
I can't figure out how to test these views using unittests
I need to test this code using unittest help me figure it out show how they are tested def post(self, request, pk): form = ReviewForm(request.POST) movie = Movie.objects.get(id=pk) if form.is_valid(): form = form.save(commit=False) if request.POST.get("parent", None): form.parent_id = int(request.POST.get("parent")) form.movie = movie form.save() return redirect(movie.get_absolute_url()) -
I can not install psycopg2 gives an error what to do
I can not install psycopg2 gives an error what to do I just started to study and already such traps help File "C:\Users\МК\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\postgresql\base.py", line 29, in <module> raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: DLL load failed while importing _psycopg: Не найден указанный модуль. -
Connection Refused to Minio Docker instance from my Django Application
Hi im trying to connect to my Minio instance which is running inside a docker container from a django instance, which is also running inside a docker container. I keep getting this error: 2020-10-29 13:59:17,568 urllib3.util.retry DEBUG Incremented Retry for (url='/'): Retry(total=0, connect=None, read=None, redirect=None, status=None) 2020-10-29 13:59:20,773 urllib3.connectionpool WARNING Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1076)'))': / 2020-10-29 13:59:20,774 urllib3.connectionpool DEBUG Starting new HTTPS connection (6): minio:9000 My docker-compose file is the following: version: "3.7" services: db: container_name: db image: mariadb restart: always ports: - '3306:3306' environment: MYSQL_DATABASE: 'django_dev' MYSQL_USER: 'user' MYSQL_PASSWORD: 'password' MYSQL_ROOT_PASSWORD: 'password' volumes: - ./mariadb:/var/lib/mysql minio: container_name: minio image: minio/minio command: 'server /export' environment: MINIO_ACCESS_KEY: weak_access_key MINIO_SECRET_KEY: weak_secret_key ports: - '9000:9000' volumes: - ./minio:/export web: container_name: web build: context: ./django/ dockerfile: ./Dockerfile target: dev command: python manage.py runserver 0.0.0.0:8000 volumes: - ./django:/usr/src/app ports: - "8000:8000" env_file: - ./.env.dev depends_on: - minio - db phpmyadmin: container_name: db_viewer image: phpmyadmin/phpmyadmin restart: always ports: - '8080:80' environment: PMA_HOST: db MYSQL_ROOT_PASSWORD: 'password' depends_on: - db The code to set up the client: minioClient = Minio('minio:9000', access_key='weak_access_key', secret_key='weak_secret_key') minioClient.list_buckets() Im using WSL2 as development environment. Python Version 3.7.7, Django Version 3.1.2, … -
Django Class based views - Signup
I have implemented a SignUp/SignIn based on class based views. While the Login is working fine, Sign up it does not. The problem is that after trying to register user and POST method is 200, user is not created in database. BTW I think the problem is on the FrontEndbecause when i'm using a simple html file with {{ form.as_p }} it works when i'm using a template from internet it does not. Please help me to identify the reason: views.py file from django.shortcuts import render from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy class UserResisterView(generic.CreateView): form_class = UserCreationForm template_name = 'registration/register.html' success_url = reverse_lazy('login') success_message = "Your profile was created successfully" authapp1/urls.py file from django.urls import path from .views import UserResisterView urlpatterns = [ path('register/', UserResisterView.as_view(), name='register'), ] auth/urls.py file from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), # Django authentication system with package URLs path('authapp1/', include('django.contrib.auth.urls')), path('authapp1/', include('authapp1.urls')), html template <!-- Register --> <section class="our-log-reg bgc-fa"> <div class="container"> <div class="row"> <div class="col-sm-12 col-lg-6 offset-lg-3"> <div class="sign_up_form inner_page"> <div class="heading"> <h3 class="text-center">Register to start learning</h3> <p class="text-center">Have an account? <a class="text-thm" href="{% url 'login' %}">Login</a></p> </div> <div … -
Excel file downloaded through Django's StreamingHttpResponse shows 'invalid format' on opening
Django 2.2.5 | Python 3.6.12 I'm trying to create an xlsx file for download using a list of dictionaries through pandas. Since the file can become huge, I'm using StreamingHttpResponse() instead of normal HttpResponse(). The code that I have currently downloads the file but shows file format is invalid when I try and open it. I have referred to these two links as of now: https://docs.djangoproject.com/en/3.1/howto/outputting-csv/#streaming-large-csv-files Django Pandas to http response (download file) Here's the code that I am using currently: # 'emails' is the list of dictionaries # 'list_name' contains the name of file with BytesIO() as bio: writer = pd.ExcelWriter(bio, engine='xlsxwriter') dataframe = pd.DataFrame(data=emails) dataframe.to_excel(writer, sheet_name="Verify Results") writer.save() bio.seek(0) workbook = bio.getvalue() response = StreamingHttpResponse( workbook, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ) response['Content-Disposition'] = f"attachment; filename={list_name}.xlsx" return response However, if I use response = HttpResponse( bio, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ) it downloads and opens up correctly. How do I use StreamingHttpResponse with pandas so that it downloads correctly?