Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to track the value of a variable that is updated per view and in a loop?
In my app I am querying an external API that has a rate limit of 600/30000 requests per 15 minutes/day. I want to be able track - from any place in my app at any time - how many requests are left for my app. Suppose I have defined REQUESTS_LEFT variable somewhere in my app for this purpose. But now imagine that my view does multiple requests in a loop and diminishes the value of REQUESTS_LEFT on every request: def API_requests(request): for i in range(50): make_API_request() # some function making request to external API REQUESTS_LEFT -= 1 return HttpResponse('Done!') If this view is called again, the loop from the previous view call will still be running, introducing a race condition where both the old and the new loop will be updating the value of REQUESTS_LEFT (the new loop starting where the old loop was when the view was called again). As a result the variable REQUESTS_LEFT becomes useless. What would be a better way to approach this? -
NoReverseMatch at / 'celery_progress' is not a registered namespace
I'm trying to integrate this library into my django app on heroku. It's giving me this error: NoReverseMatch at / 'celery_progress' is not a registered namespace Index.html(where the error occurs): // vanilla JS version document.addEventListener("DOMContentLoaded", function () { var progressUrl = "{% url 'celery_progress:task_status' task_id %}"; CeleryProgressBar.initProgressBar(progressUrl); }); Any ideas? -
Django OAuth with Non-Social Provider
I have an application for which I'd like to make use of SSO which is supplied by many schools and companies via OAuth. There are existing plugins for Github, Google, Facebook, Twitter and the likes but I can't seem to find anything regarding these other providers. Is there any way to go about this? -
How to mysql config in django setting
I tried to connect MySQL in Django. but it's throwing an error on django.db.utils.OperationalError: (1044, "Access denied for user ''@'localhost' to database 'yourdbname'") how to solve this error . Setting DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'yourdbname', 'HOST': '127.0.0.1', 'PORT': '3306', }, } I tried to different ways to solve this issue. but it's not working This is first time I am working on muysql to connect django. -
How to send files from NodeJs to Django app using axios?
Am trying to send files from Nodejs app to Django app, but when I try to test if the file is sent, it shows that there is no files! Nodejs: appJ.get("/testFiles", (req, res) => { var formData = new FormData(); formData.append("file", fs.createReadStream('src/assets/TextFiles/104931574076657597.txt')); axios.post("http://127.0.0.1:8000/testFile/", formData).then(result => { console.log(result.data); }).catch(err => { console.log(err); }) }) Django: @csrf_exempt def testFile(request): if (request.method == "GET"): return HttpResponse("Ok") elif(request.method == "POST"): print("Hello") print(request.FILES) return HttpResponse("OK") How can I solve that?