Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you post a file along with some other data using axios react?
So my model looks like this. # posts/models.py from django.db import models class Post(models.Model): title = models.TextField() cover = models.ImageField(upload_to='images/') def __str__(self): return self.title And I know you can upload file using axios like this fileUpload(file){ const url ='http://example.com/file-upload'; const formData = new FormData(); formData.append('file',file) const config = { headers: { 'content-type': 'multipart/form-data' } } return post(url, formData,config) } But I want to upload the image along with the title. How do I do that in axios? -
I want to edit only one database field with one click with django
I have a Movie database and a boolean field init. I want to click a button and change that boolean field's value. But I couldn't manage to get Movie pk from the url. I'm getting this error: 'WSGIRequest' object has no attribute 'kwargs' Here is my views: @login_required def one_cikan_button(self, **kwargs): pk = self.kwargs['pk'] print(pk) film = Movies.objects.get(pk=pk) try: film.featured = False film.save() return redirect('/headoffice/onecikanlar/') except Exception as e: return redirect('/headoffice/onecikanlar/') return redirect('/headoffice/onecikanlar/') My urls: path('onecikanlar/kaldir/<pk>/', views.one_cikan_button, name="onecikankaldir"), My template: <a href="/headoffice/onecikanlar/kaldir/{{obj.pk}}/" title="Sil"><i class="notika-icon notika-trash" style="font-size:14pt; color:black;"></i></a> My models: class Movies(models.Model): featured = models.BooleanField(default=False) How can I solve this? Or can I use UpdateView with custom settings? -
Django: How to log out a user using Javascript's window.confirm()
I am making a web app using Django/Python. There is a navigation at the top of the web app, and if a user clicks on the 'logout' link a pop-up window using Javascript's window.confirm() asks them if they are sure that they want to log out. I have the following in logout.js: function logout() { if(window.confirm("Are you you sure that you want to log out?")) { window.open("index.html"); } return; } If a user selects 'OK' in the pop-up that is displayed, I want the app to log the user out and display the home page of the app (represented by index.html). However, to log the user out I need to do this in views.py. I have the following code in views.py: def logoutUser(request): if request.POST: if request.POST.get("confirm-btn"): logout(request) return render(request, 'index.html') if request.POST.get("cancel-btn"): return redirect('/dashboard/') return render(request, 'logout.html') I have a page called logout.html which has two buttons, and if a user clicks the confirm button they are logged out and taken to the home page. However, I want a pop-up to be displayed instead. My question is, how can I connect the Javascript code for the logout pop-up with the backend code in views.py that deals with the user … -
Haystack/Whoosh convert string to bytes-like object? "Cannot use a string pattern on a bytes-like object" error
On my Django (2.2.7, Python 3.7) project, I use Haystack(2.8.1) and Whoosh(2.7.4) for fulltext search. When searching, I always get Cannot use a string pattern on a bytes-like object error. I know, in general, why this error happens, but I don't know hot to avoid it. I pass a proper string keyword to haystack/whoosh functions, but it gets probably converted to bytes-like object somewhere inside the above libraries. E.g. I give it a string somestring, but it becomes b'somestring' in the file "/usr/local/lib/python3.7/site-packages/haystack/inputs.py" in self.exact_match_re.findall(query_string) function. Local vars at that moment: __class__ <class 'haystack.inputs.AutoQuery'> query_obj <haystack.backends.whoosh_backend.WhooshSearchQuery object at 0x7fea4c19c550> query_string b'somestring' self <AutoQuery 'somestring'> The whole stack trace: ERROR 2019-11-23 01:17:51,136 middlewares 5013 140644284933888 http://www.my_project.loc/hledat?q=ATIKA&x=3&y=16 Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/haystack/views.py", line 51, in __call__ return self.create_response() File "/my_project/search/views.py", line 57, in create_response for item in self.results: File "/usr/local/lib/python3.7/site-packages/haystack/query.py", line 154, in _manual_iter if not self._fill_cache(current_position, current_position + ITERATOR_LOAD_PER_QUERY): File "/usr/local/lib/python3.7/site-packages/haystack/query.py", line 231, in _fill_cache results = self.query.get_results(**kwargs) File "/usr/local/lib/python3.7/site-packages/haystack/backends/__init__.py", line 638, in get_results self.run(**kwargs) File "/usr/local/lib/python3.7/site-packages/haystack/backends/__init__.py", line 550, in run final_query = self.build_query() File "/usr/local/lib/python3.7/site-packages/haystack/backends/__init__.py", line 693, in build_query final_query = self.query_filter.as_query_string(self.build_query_fragment) File "/usr/local/lib/python3.7/site-packages/haystack/backends/__init__.py", line 381, in … -
How can a result from one class can be used in another class. I'm trying to user my SearchResultsView result as the author in PostCreateView
class SearchResultsView(ListView): model = User template_name = 'all_users/doctor/search.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = User.objects.filter(Q(username__icontains=query)) return object_list class PostCreateView(LoginRequiredMixin, CreateView): template_name = 'all_users/doctor/post_form.html' model = Post fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.object_list return super().form_valid(form) -
why am I not able to get a dropdown on my html template?
I have added a screenshot of how my html template looks in the browser. I'm not getting a dropdown in my form for Name label. I am getting the desired output(dropdown) in my model. I have already gone through the official documentation of Django, but was not able to find a solution. I am new to Django.what should I do? models.py from django.db import models class Record(models.Model): CHOICES = ( ('john', 'JOHN'), ('sam', 'SAM'), ('lucy', 'LUCY') ) date = models.DateTimeField(auto_now_add = True) emp_name = models.CharField(max_length=10, choices=CHOICES) amount = models.PositiveIntegerField(default=0) views.py from django.http import HttpResponse from django.views.generic import FormView from .models import Record from .forms import RecordForm class home(FormView): template_name = 'myapp/home.html' form_class = RecordForm def form_valid(self, form): return HttpResponse("Sweeeeeet.") forms.py from django import forms from .models import Record CHOICES = [ ('john', 'JOHN'), ('sam', 'SAM'), ('lucy', 'LUCY') ] class RecordForm(forms.ModelForm): name = forms.CharField(label='Name', widget=forms.Select(choices=CHOICES)) amount = forms.IntegerField() class Meta: model = Record fields = '__all__' urls.py from django.urls import path from django.contrib.auth import views as auth_views from .views import EmployeeListView, home from . import views urlpatterns = [ path('', home.as_view(),name='home'), path('logout/', auth_views.LogoutView.as_view(template_name = 'myapp/logout.html'), name='home-logout'), path('profile/', views.profile, name='home-profile'), path('employee/', EmployeeListView.as_view(), name='home-employee'), ] home.html <style type="text/css"> .form-container { border-radius: 10px; padding: … -
i want to must be require login by the user in django
i am beginner in django and i want to that the user must be login if user want to see the detail of the property [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/MXhbW.jpg View Detail apply restriction on this View detail button that if user not login then user can't see the property details -
Django rest framework. Return multiple models nested
I'm trying to create a combined viewset that displays data in a nested format from three django models. I'm receiving an error when I try to return the viewset. Got AttributeError when attempting to get a value for field `runner` on serializer `CombinedSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Runner` instance. Original exception text was: 'Runner' object has no attribute 'runner'. class CombinedSerializer(serializers.Serializer): event = EventSerializer(many=True) market = MarketSerializer(many=True) runner = RunnerSerializer(many=True) class Meta: fields = ('event' , 'market', 'runner') class CombinedViewSet(mixins.ListModelMixin, viewsets.GenericViewSet, mixins.RetrieveModelMixin): queryset = Runner.objects.all() serializer_class = CombinedSerializer For some reason when I remove runner from the serializer Event and Market display in my api in nested format. When I add Runner I get the above error. How can I fix this and display all three in my API? -
CORS is not enabling in django backend?
I'm trying to enable CORS for my django project which is interacting with ionic on frontend.When i send a post request to django backend, browser shows following error message:- Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:3000/api/customer. (Reason: CORS header 'Access-Control-Allow-Origin' missing). While console shows options request method instead of Post .I enabled my custom middleware for handling CORS which is:- class CorsMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) response["Access-Control-Allow-Origin"] = "*" return response But it still keeps showing same error.My ionic server is running at http://127.0.0.1:8100 while django backend is running on http://127.0.0.1:3000 -
i try ajax partial refresh html,but it does't work
I'm trying to load the page locally with Ajax, but the following code doesn't work. My idea is to pass the 'MSG' information of 'views' to Ajax and refresh the page locally without loading the entire page. If the input does not meet the requirements, the front end rejects the submission and gives a prompt message. views.py def login(request): hashkey = CaptchaStore.generate_key() image_url = captcha_image_url(hashkey) captcha = {'image_url': image_url, 'hashkey':hashkey} if request.POST: username = request.POST['username'] password = request.POST['password'] key = request.POST['hashkey'] capt = request.POST['captcha'] if username and password: if captchautil.is_valid(capt, key): user = auth.authenticate(username=username, password=password) human = True if user: auth.login(request, user) return redirect('/') else: msg = '用户名密码错误' else: msg = '请输入正确的验证码' else: msg = '请输入用户名与密码' return render(request, 'login.html', locals()) return render(request, 'login.html', locals()) login.html {% block content %} <div id="login" class="login"> <form action="/login/" method="post" class="navbar-form"> {% csrf_token %} <div id="input" class="form-group"> <input type="username" name="username" class="form-control" placeholder="请输入手机号或邮箱" id='user' title="请输入手机号或邮箱"><br><br> <input type="password" name="password" class="form-control" placeholder="密码" id='pwd' title="请输入密码"><br><br> <img src="{{image_url}}" alt='验证码' id='id_captcha'> <span><a href="#" id="refresh_captcha">看不清验证码?刷新</a></span> <br> <input id='captcha' placeholder="请输入验证码" name="captcha" class="form-control" type="text" data-toggle="tooltip" data-placement="bottom" title="请输入验证码"> <input value="{{hashkey}}" type="hidden" name="hashkey" id='hashkey'> <br> <button type="submit" class="btn btn-primary form-control" name="click" id='click'>登录</button> </div> <p style="margin-left: auto;" id="msg">{{ msg }}</p></div> </form> <div style="margin-left: 3%"> <span> <a href="">忘记密码了?</a> … -
Run Celery Interval task every 95/100/105 minutes
I use django_celery_beat and try to set up tasks to run every 95/100/105/120 minutes. Are these settings correct? On what time it will be run? -
'Section4' object has no attribute 'user'
I am trying to customize the default django admin and add the total field in the footer. I don't know if this is the correct way to do. @admin.register(Section4, site=admin_site) class Section4Admin(ReadOnlyParamsMixin, admin.ModelAdmin): change_list_template = 'admin/section4/section4/total_review_count.html' def get_total(self, user): total_n = CarePlanNeed.objects.all().count() td = datetime.timedelta(29) last_review = timezone.now() - td total_review_upto_date = len(Counter([p['latest'] for p in self.get_careplan(user).values('resident', 'aspect_of_life').annotate( latest=Max('history_date')).filter(latest__gt=last_review).order_by() if p['latest']+td>timezone.now()])) total_review_tobe_updated = len(Counter([p['latest'] for p in self.get_careplan(user).values('resident', 'aspect_of_life').annotate( latest=Max('history_date')).filter(latest__gt=last_review).order_by() if p['latest']+td<timezone.now()])) total_review_added = self.get_careplan(user).values('resident', 'aspect_of_life') total_review_tobe_added = total_n * 17 - len(total_review_added) return total_review_upto_date, total_review_tobe_updated, total_review_tobe_added def changelist_view(self, request, extra_context=None): total_review_upto_date, total_review_tobe_updated, total_review_tobe_added = self.get_total(request.user) my_context = { 'total_review_upto_date': total_review_upto_date, 'total_review_tobe_updated': total_review_tobe_updated, 'total_review_tobe_added': total_review_tobe_added } return super(Section4Admin, self).changelist_view(request, extra_context=my_context) total_review_count.html: {% extends "admin/section4/section4/change_list.html" %} {% load i18n admin_urls %} {% block result_list %} {{ block.super }} <footer style="color:blue;"> <p >The total review upto date: {{ total_review_upto_date}}<br> </p> <p>The total review to be updated: {{ total_review_tobe_updated}}<br></p> <p>Total review to be added : {{ total_review_tobe_added }}</p> </footer> <p> {{ user }}</p> {% endblock %} Error : AttributeError at /section4/section4/ 'Section4' object has no attribute 'user' home/bishwa/PycharmProjects/johnson/section4/admin.py in changelist_view, line 430 I actually wanted to add the total_review_tobe_updated, total_review_tobe_updated, total_review_tobe_added in the footer of the list_view of django admin. -
How to render Django model form drop down manually in the template?
Here is my model form class CategoryCreateForm(forms.ModelForm): class Meta: model = Category fields = [ 'nature', 'name', 'description', ] The field nature is a foreign field. I know I can render this field in the template using {{ form.nature }} but I would like to render the form manually without the help of Django or crispy forms. I have managed to do so for the other fields but don't know how to do it for a select field of a model form. I am looking for a solution similar to the following <select class="custom-select custom-select-sm{% if form.nature.errors %} is-invalid{% endif %}" id="{{ form.nature.id_for_label }}" name="{{ form.nature.html_name }}"> {% for nature in form.nature.objects %} <option value="{{ nature.id }}">{{ nature.name }}</option> {% endfor %} </select> -
Normalize Mobile Numbers using Python
I have a string of digits, how can I format this as a mobile number? I am trying to create a python def that takes a string and normalizes them into a format I can use. I am trying to remove all symbols and spaces and just leave the numbers. As well as add +98 to the beginning Some trivial examples: 916 222 3344 > +989162223344 09375554433 > +989375554433 +98 912 999 88 77 > +989129998877 -
How to change the value of an href attribute with JS?
I want to change the value of the href attributes of the anchor tags on my website when the user clicks a button. In particular I want to change the value of a GET parameter in this url. (If you are not familiar with the {% url 'select_question' %} and {{ subcategory.name }} tags just ignore them they are Django template tags.) The text on the button changes but the url in the href doesn't. Mode is always "unsolved". What am I doing wrong? Thanks! <button id="changeModeBtn" class="btn btn-primary" type="button" name="button" onclick="change()">Unsolved Questions</button> <a class="question_link" href="{% url 'select_question' %}?subcategory={{ subcategory.slug }}&mode=unsolved">{{ subcategory.name }}</a> <script type="text/javascript"> function change(){ var btn = document.getElementById("changeModeBtn"); var link = document.getElementsByClassName("question_link"); if (btn.textContent=="Unsolved Questions") { btn.textContent="Solved Questions"; link.setAttribute("href", "{% url 'select_question' %}?subcategory={{ subcategory.slug }}&mode=solved"); } else if (btn.textContent=="Solved Questions") { btn.textContent="All Questions"; link.setAttribute("href", "{% url 'select_question' %}?subcategory={{ subcategory.slug }}&mode=all"); } else { btn.textContent="Unsolved Questions"; link.setAttribute("href", "{% url 'select_question' %}?subcategory={{ subcategory.slug }}&mode=unsolved"); } } </script> -
Groupby time intervals
I have a model with a DateTimeField and I want to run some queries so I can get sum of other fields, grouped by specific time intervals like: 5min, 10min, 1hr, 3hr and etc. I also need the intervals begining and end. count = models.IntegerField(null=False) time = models.DateTimeField(null=False) -
I want to update my student record in the database, but its not working
The first problem is that when the update form is appeared date-of-birth field is not getting data from the database. The Second thing is that whenever i click on the submit button it will not update my values in the databse. The Third thing is after i click on the update or submit button it will automatically redirect to me in the insertion form which i don't want to be there (and i not even give the link or render to that page and i don't understand what is going on here beacause instead of it it will need to show my editstudent.html page not insertstudent.html page) and YES!!! MY UPDATE IS ALSO NOT WORKING...... PLEASE HELP ME OUT AT THIS....... editstudent.html PAGE:- {% extends 'student/index.html' %} {% block content %} <div class="col-md-6"> <!-- general form elements --> <div class="card card-primary"> <div class="card-header"> <h3 class="card-title">Update Student Here</h3> </div> <!-- /.card-header --> <!-- form start --> <form action="{% url 'studentinsert' %}" role="form" method="POST"> {% csrf_token %} <div class="card-body"> <div class="form-group"> <label for="exampleInputEmail1">Student ID</label> <input type="text" class="form-control" name="id" placeholder="Enter Student ID" value="{{ student.sid }}"> </div> <div class="form-group"> <label for="exampleInputPassword1">First Name</label> <input type="text" class="form-control" name="firstname" placeholder="Enter First Name" value="{{ student.first_Name }}"> </div> <div … -
How to sum values in an HTML table column
I have checked every conceivable questions available on SO but did not find one that solved my problem. The closest I got was on this. In my Django app I have a dynamic table with columns for price, quantity and amount (price * quantity) besides other fields. I am looking to get the sum total of "amount" column. Rows can be added at runtime and for my test purpose I have kept the default number of rows to 3 (extra = 2 in inlineformset_factory). I am using the following jquery for the purpose of calculating values in "amount" column: $(document).ready(function() { mySum=0; $("#process").click(function() { $(".itemPriceClass").each(function() { mySum += parseFloat($('.itemPriceClass input').val()); alert('The sum of item amount is: ' + mySum); }); }); }); where: "itemPriceClass" is <td> class in the Amount column. "process" is the id of a button to get the function to execute. However, when executed (with the default three rows of the table and only the first row having been filled in), I find that the function is executed three times (though the last two rows do not have any data in them) and the final total comes to exactly three times the value in that of the … -
Effeciant way to load images from directory using django template
I have hundreds of images under /statics/projectname/*.png , usually i load the images like following. {% extends "base.html" %} {% load static %} {% load staticfiles %} {% for result in projects %} <div class="banner-img"> <img src="{% get_static_prefix %}/{{result.project_name}}/{{ result }}.png" alt="Image 1"> </div> {% endfor %} But i noticed that it is time consuming task, app takes enough time to load the images and render. What is the most effecient and faster way to fix this. -
When i run the scrapy its shows an error like __import__(name) ImportError: No module named home in ubuntu
when i run the scrapy it shows an error like, import(name) ImportError: No module named home,how to solve this issue? import os import sys import django DJANGO_PROJECT_PATH = '/home/user/Documents/myproject' DJANGO_SETTINGS_MODULE = 'myproject.settings' sys.path.insert(0, DJANGO_PROJECT_PATH) os.environ['DJANGO_SETTINGS_MODULE'] = DJANGO_SETTINGS_MODULE BOT_NAME = 'example_bot' django.setup() -
To create multiple Django projects on one virtual environment , is this good or bad
To create multiple Django projects on one virtual environment , is this good or bad ! i am a beginner in Django Python... -
Is there an app for Django to manage fields of models?
Like in phpmyadmin, we have an visual interface to manage fields. Can we do the same thing in Django? -
group by two varlues and get the third values
I have this Django model with three CharFields, which I want to run a query on to get the existing values for the two of them, and for each combination get the existing values of the third field. a = models.CharField(null=False, max_length=8000) b = models.CharField(null=False, max_length=8000) c = models.CharField(null=False, max_length=8000) if assume that these values are in the database: a | b | c | --------------- a1 | b2 | c3 | a1 | b2 | c1 | a2 | b2 | c3 | a1 | b3 | c3 | a1 | b2 | c2 | I want some result in this form : {"a1-b2" : [c3, c1, c2], "a2-b2" : [c3], "a1-b3" : [c3]} or {"a1" : {"b2":[c3, c1, c2], "b3": [c3]}, "a2": {"b2" : [c3]}} -
django.contrib.sites table can not find in xadmin
I relpaced admin with xadmin,however sites app in admin instead of xadmin i want to know the reason,thanks! -
Django Connect remote Mysql OperationalError 2026
I'm using Django + mysql for days. And this morning I suddenly found that I cannot get connect with the remote mysql. % python manage.py makemigrations it raise django.db.utils.OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed') also when python manage.py runserver Here's my environment: macOS 10.15 + Django 2.2.6 + MySQL 5.7 (on a remote server, ubuntu 18.04) + python 3.6.8 (use conda env) I've looked for some solutions like: downgrade openssl Package openssl conflicts for: openssl=1.0.2r python=3.6.8 -> openssl[version='>=1.1.1a,<1.1.2a'] add use_pure=True in my .conf file nothing changed add skip_ssl in my .conf file nothing changed note On the server (which I deploy my site, ubuntu 18.04) my site run well using gunicorn + Nginx All the things worked well until today. The site broke when I found this issue but work well when I restart it. I guess maybe some update on the server (automatically upgrade) to cause the problem, but haven't find it yet. some of my code # setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': mysqlPath, 'init_command': 'SET default_storage_engine=INNODB', }, } } # my_remote.cnf (which define the 'mysqlPath' in setting.py) [client] database = mydatabase user = myusername password = mypassword default-character-set = utf8 host …