Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i want to import all classes from a model.py which is not in my app modules in Django
in Django, my model.py is out of my App modules I want to import all the classes from that model.py to all modules. I searched a lot I didn't get anything can anyone help me -
How to deserialize nested django object
I'm not really sure how I'm able to access the data of a nested serializer, with a one-to-many relation. Here's my models: class Album(models.Model): id = models.CharField(max_length=255, null=True, blank=True) name = models.CharField(max_length=255, null=True, blank=True) class Title(models.Model): name = models.CharField(max_length=255, null=True, blank=True) album = models.ForeignKey( Album, related_name='titles' ) then I have 2 serializers: class AlbumSerializer(serializers.ModelSerializer): titles = TitleSerializer(many=True) class Meta: model = Album fields = ['id', 'name', 'titles'] def create(self, validated_data): album = Album.objects.create( id=validated_data.get('id'), name=validated_data.get('name') ) titles = validated_data.pop('titles') for title in titles: title['album'] = album _title = Title(**title) _title.save() return album class TitleSerializer(serializers.ModelSerializer): class Meta: model = Title fields = ['name'] To deserialize and save I run the following: album = AlbumSerializer(data=input_json) album.is_valid() album.save() my problem is now, that I'm unable to access the items. Accessing the type of album.instance.titles gets me <class 'django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager'>. How can I get the titles out of it, or what am I doing wrong that I do not get a list of Titles in there? -
Django manage.py migrate command cannot access Linux environment variables
Python cannot access environment variables while running any command. For example, after running python3 manage.py migrate an error occurs: django.db.utils.OperationalError: (2006, "Access denied for user 'dbmasteruser'@'0.0.0.0' (using password: YES)") But if I insert a plain string value for database password instead of os.environ.get('PASSWORD'), command works fine. All environment variables are written in setenv.sh file, but I have also tried to set them alternatively using command export PASSWORD=password. Executing command using sudo doesn't work either. However, Apache deployment server can read those environment variables without any issues, but the problem occurs while running migrations or any other command. How can I solve it? -
Static files doesn't load anymore - Django
In the beginning everything worked perfectly fine, but now I have a problem where my static files doesn't load. I think this is a very weird problem since I didn't really touch anything that could've had an influence on the problem when it happened. Everything else is working fine, I just can't get the static files for some reason. I sometimes get a 200 http response trying to get the static files like so: [20/Aug/2020 16:12:51] "GET /order/checkout/ HTTP/1.1" 200 2029 [20/Aug/2020 16:12:51] "GET /static/my_pizza_place/js/client.js HTTP/1.1" 200 2194 [20/Aug/2020 16:12:51] "GET /static/css/master.css HTTP/1.1" 200 80 [20/Aug/2020 16:12:51] "GET /static/css/global.css HTTP/1.1" 200 530 But it's still not applying the styling to my html code. I usually just get a 304 http response on my client.js file though. I feel like I have tried almost everything at this point, so I hope you guys can help me figuring out what the problem is. My files: SETTINGS.PY BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] BASE.HTML <!DOCTYPE html> {% load static %} <html lang="en"> <head> ... <link rel="stylesheet" href="{% static 'css/master.css' %}"> <link rel="stylesheet" href="{% static 'css/global.css' %}"> <script src="{% static 'my_pizza_place/js/client.js' %}" defer></script> </head> <body> <div class="container mycontent"> {% block … -
Require second login for users on Django based site
I have a Django 2.2 based project that uses a custom user model, the built-in Auth app and Django-All-Auth for user management. Almost every page on the site is behind a login and we use varying levels of permissions to determine what can be accessed a user. So far, so good, but now I'm being asked to designate everything behind a specific part of the site as "sensitive", requiring a second login prompt. What this means is that the client wants to see a login appear when they try to access anything under /top-secret/ the first time in a set time, say 30 mins, regardless of whether they're already logged in or not. I've dug around on the internet for ideas on how to do this, but so far I've been unable to find a good solution. Has anyone here had any experience with something similar, and if so, could they point me in the right direction? -
Python intermittent OpenSSL error: FileNotFoundError: [Errno 2] No such file or directory
I'm getting an intermittent error on my production Django website (running under UWSGI) when trying to use the kubernetes client library. The error seems to be urllib3, or perhaps OpenSSL. The strange thing is, I can simply restart my server and the problem goes away, but only temporarily. After a while I start seeing this error again: Traceback (most recent call last): File "/srv/hive/lib/python3.6/site-packages/urllib3/util/ssl_.py", line 353, in ssl_wrap_socket context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data) FileNotFoundError: [Errno 2] No such file or directory This is extremely difficult to troubleshoot, because restarting the server makes the problem go away for a few hours. I added some extra logging to the load_verify_locations function in urllib3/util/ssl_.py to see what file it's trying to open. The ca_certs argument is passing in a temp file, /tmp/tmp2xng8a6e. The other two arguments are None. So, why a temp file, and why is it missing? Is there a reason why the temp file would get deleted, or why urllib3 might not be creating the temp file in the first place? Here's the full exception with traceback: Aug 20 10:36:05 ERROR django.request: Internal Server Error: /code/projects/test-project/ Traceback (most recent call last): File "/srv/hive/lib/python3.6/site-packages/urllib3/util/ssl_.py", line 353, in ssl_wrap_socket context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data) FileNotFoundError: [Errno 2] … -
How to connect oracle 11g with django project?
I am new to Django and Oracle sql.I need to connect my Django project with my Oracle database.I am using Oracle 11g and Django 3.0 Can you please explain the whole procedure to connect them form a to z? -
Post-save method to handle calculations in django admin forms
I have two models: Estimate and Product. Product's form is included as TabularInline inside Estimate's admin form. Each instance of Estimate creates at least one instance of Product. What I'm trying to do is calculate a total of Product's subtotals and have it show up in the estimate model after saving the instance for the first time. Code could probably explain what I'm trying to do better. I tried overriding Estimate's Save method and I tried post-save signals (it's commented out). Everything works the way I want it to, except I have to save the model instance twice to trigger the calculate function. My question is, is there a way to cut this process short? Have it entirely done with the first save? models.py class Estimate(models.Model): #other irrelevant fields tax = models.DecimalField(max_digits=8, decimal_places=2, validators=[MinValueValidator(0.0)], blank=True, null=True) total = models.CharField(max_length=15, blank=True, null=True) def save(self, *args, **kwargs): subtotals = Product.objects.filter(estimate_id=self.id).aggregate(pr_total=Sum('subtotal'))['pr_total'] or 0 self.total = subtotals if self.tax: self.total = subtotals + ((subtotals * self.tax) / 100) super(Estimate, self).save(*args, **kwargs) # @receiver(signals.post_save, sender=Estimate) # def calculate_total(sender, instance, **kwargs): # subtotals = Product.objects.filter(estimate_id=instance.id).aggregate(pr_total=Sum('subtotal'))['pr_total'] or 0 # instance.total = subtotals # if instance.tax: # instance.total = subtotals + ((subtotals * instance.tax) / 100) # signals.post_save.disconnect(calculate_total, … -
error occuring at test file in Inspection/Defect class in tests.py line 29
This is the code that's giving me trouble. I've asked about it in the last 2 hours and no one is responding to my question at Inspection/Defect Problem. If anyone can show me how to fix the problem, it would be appreciated!!! -
How to Format Dates in Python?
I have a field in a query set of type DateTime.DateTime: "datetime.datetime (2020, 6, 16, 22, 29, 43, tzinfo = )", I want to change the format of this field to: "%Y -%m-%d %T", how could I do it ?, I tried as follows but it tells me the following:" 'NoneType' object has no attribute 'strftime' ". CODE: test.append({'device_id': d.device_id_id, 'device_name': d.device_id.device_name, 'startdatettime': (d.startdatetime).strftime('%Y-%m-%d %T'), 'enddatetime': (d.enddatetime).strftime('%Y-%m-%d %T'), 'active': d.active, 'loggeduser': d.logged_user, 'area_id': d.area_id.id, 'area_name': d.area_id.area_name, 'digitaloutput_user_description': d.lightstate_id.do_id.user_description, 'lighstate_user_description': d.lightstate_id.user_description, 'color': (d.lightstate_id.do_id.color).replace('w3-', ''), 'shift_startdatetime': d.shift_startdatetime, 'shift_enddatetime': d.shift_enddatetime, 'shift_name': d.shift_name}) -
how to display the menu name in drop-down menu dynamically in Django
this is my index.html file <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Reports<span class="caret"></span></a> <ul class="dropdown-menu"> <li class="dropdown-header">Reports</li> <li> <div class="buttons pull-right"> <a href="{% url 'report:reporttest' %}" class="btn btn-xs btn-success" title="Add"><i class="fa fa-plus"></i></a> </div> <a href="{% url 'report:reporttwo' %}">Report one</a> </li> {% if name %} <li> <a href="{% url 'report:add' %}">{{name}}</a> </li> {% endif %} </ul> </li> the view.py file def reportone(request): return render(request, 'report_one.html') def reporttwo(request): return render(request, 'report_two.html') def reporttest(request): return render(request, 'add_report.html') def add(request): if request.method == "POST": #rept=ReportName.objects.all() #rept=ReportName() src=request.POST.get('src') width=request.POST.get('width') height=request.POST.get('height') name=request.POST.get('name') #context={'rept':rept} #if request.method == "POST": return render(request, 'report_one.html', {'src':src, 'width':width, 'height':height, 'name':name}) else: return render(request, 'report_one.html') i have created report successfully....but i want the report name which i was creating will display on the dropdown menu .... using the above code i can able to see the created report name in the dropdown but the problem is when we click on the report name which is shown in the dropdown is not showing the created report and report name will also remove from the dropdown menu .... i want all the report that i created before will show in the dropdown after the page get reload or reopen the page i believe … -
Correct way to update django to a specific (but not most recent) version via pipenv
I am currently using django==2.2.5, managing my dependencies via pipenv and would like to upgrade to django==2.2.15 Unfortunately the pipenv documentation does not say anything regarding the option of specifying a certain version when using pipenv update - hence my problem/question: Since the command pipenv update django would update my django to the latest 3.1 version but I only want to update to version 2.2.15 I have to use pipenv install django==2.2.15. True or Not? And if not, what would be the correct way? Since I am doing this the first time, I am amfraid to mess things up , so just wanted to be on the safe side, before proceeding.... -
Using a Real time update on a web app will that crash the server?
I have an app that consist of two types of users one type can post questions and the other type can answer now I'm integrating a real time updates when a user add a question all the other users get this question immediately without refreshing the page I using Pusher for that and once a user adds a question I send an alert to all the connect users nad once they receive this alert they make an ajax requests and get all the question again, my question is , is this a valid way to do that and can this method cause problems later on when deploy app to the server as you can see when I send the alert all the users will make an ajax request to the server at the same time will that cause my server to crash please help me thanks. -
how to preview checked box in another html file and show in the current html
I have two htmls. One is redirected as a result of a function and is as follows: first.html <div id="ck-button"> {% for item in items %} <label class="btn btn-custom gender-label m-1"> <input type="checkbox" id="myCheck" value="{{ item.0 }}" onclick='myFunction();'> <span> {{ item.1 }} </span> </label> {% endfor %} </div> and another one is the main html file which contents everything. second.html: <form method="POST" action="" enctype="multipart/form-data"> <fieldset class="form-group"> {% csrf_token %} <div class="content-section"> {{ form|crispy }} </div> <div> <label for="content"> choose items:</label> <p class="text-muted" id="previewItems"> </p> </div> </fieldset> <div class="form-group mt-7"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> <script> function myfunction() { var checkBox = document.getElementById("myCheck"); var text = document.getElementById("previewItems"); if (checkBox.checked == true){ text.style.display = "block"; } else { text.style.display = "none"; } } </script> Is it possible to get checked items in another html file and show it synchronously in the current html? or is there any other solution that could help me? Thanks -
keep the username even when I refresh the page django
I want to refresh my web page, and keep the username logged in. views: currentUser = [] def evt_stat(request): if request.method == 'POST' and 'login' in request.POST: username =request.POST['email'] password =request.POST['password'] currentUser = authenticate(username=username, password=password) currentUser.save() if currentUser is not None: return render(request, 'evt/index.html', {'currentUser': currentUser}) else: ErrorLogin= True return render(request, 'evt/login.html', {'ErrorLogin': ErrorLogin}) . . . return render(request, 'evt/index.html', {'ErrorLogin': ErrorLogin}) .html : <div class="mr-2 d-none d-lg-inline text-gray-600 small"> {{currentUser.first_name}} {{currentUser.last_name}}</div> when i do this i got this error return render(request, 'evt/index.html', {'uploaded_file_url': uploaded_file_url,'ErrorLogin': ErrorLogin}) UnboundLocalError: local variable 'ErrorLogin' referenced before assignment the problem here if I don't put the line: return render(request, 'evt/index.html', {'ErrorLogin': ErrorLogin}) the first time I log in I see the user's first and last name, but when I refresh the page, I lose the user's first and last name information. what can I do to keep the username even when I refresh the page -
Create database table with angular 10 and django rest framework
I wanted to allow the user/admin to create a table with inputs in the html (using angular for frontend), the columns desired with the types and options. Send those informations to Django (using rest framework) and to be created a model -> table in the database. My database is a mongodb I completely don't know how to do. Thanks in advance for your time ! -
Django-Rest-Framework dynamic routing
I have a set of analogue objects that I would like to return with a single view MY_OBJECTS = ['a', 'b', 'c'] class AnyObjectViewSet(ViewSet): def initial(self, request, *args, **kwargs): super().initial(request, *args, **kwargs) # How can I get this? self.obj_name = kwargs['obj_name'] def list(self, request, **kwargs) data = get_data(self.obj_name) # some function to retrieve dynamic data return Response(data) ### urls.py router = DefaultRouter() for obj in MY_OBJECTS: # How do I pass parameter to my router in a way that my viewset gets it? router.register(f"/api/{obj}", AnyObjectViewSet, basename=obj) My question: Is there a way to have one view for all the objects, setting the object name by url parameter? In theory I could make a factory that creates a ViewSet Class for any of my objects, but this seems very tedious. -
Javascript working only after I open a modal
So I have a problem where my script for a filter/search list used to work, added a few lines of code to open a modal when a certain event occurs and now strangely when I go on my page, I can't use the search/filter list, but when I open the modal and close it, then I can use it..? It looks like it has to process the modal script first to be able to use the search/filter script. I am working with Django and MySQL, here are the relevant lines of code: .html ( first lines are about the search function, the second part is the modal and third block is the table used in the search/filter function and the conditions for opening the modal ) <div class="search-right"> <input type="text" id="mySearchInput" placeholder= " Search a stock.." title="Stock Search" style="float:left"> </div> {% if warning %} <div id="myModalAddaStock" class="modalAddaStock"> <div class="modal-content"> <span class="closeAddaStock">&times;</span> <p>{{warning}} {% if stock_to_add %}{{stock_to_add}} {% endif %}{% if stock_to_replace %}{{stock_to_replace}} or {{flex}}{% endif %}</p> </div> </div>{% endif %} <div class="grid-itam-2bottom"> <table id="myTable1" class="myTable"cellspacing="0" cellpadding="1" border="1" width="100%"> <tr class="stockheader"> <th width="8%" style="text-align:center;">Symbol</th> <th width="35%"style="text-align:center">Company Name</th> <th width="8%" style="text-align:center">Sector</th> <th width="7%" style="text-align:center">Streak</th> <th width="12%"style="text-align:center">Market Cap</th> <th width="8%" style="text-align:center">Return</th> <th width="6%" … -
How to use SerializerMethodField as choices of ChoiceField?
I have a serializer as below, class customerSerializer(serializers.ModelSerializer): drop_list = serializers.SerializerMethodField(read_only=False) cust_choices= serializers.ChoiceField(choices=drop_list,allow_blank=True,allow_null=True,many=True) ............. ............. ............. def get_drop_list(self,obj): .......... return list If I try to create the choice using Serializermethodfield.It throws me the below error, TypeError: 'function' object is not iterable Please help to sort out. If there is another way.Suggest me. Thanks in advance. -
I cant go to the model I'm trying to update
My django Url## url(r'^Updatemodel/', Updatemodeldata.as_view()) Redirection takes place with url. No problem in view. I have defined everything but the model ı want does not come. Please help. -
How to make checks in the form when entering a field in Django
I'm a novice user of django. My intention is to add a check in the form to verify that the name entered by the user for "GroupCalenadr" is not already present. In case it is already present, return an error message otherwise everything is ok. My problem is that I don't know what works I have to use in the form.py to make these checks. Thank you very much to who will help me. In form.html: {% block content %} <form method="post"> {% csrf_token %} <table class="form form-table"> {{ form }} <tr><td colspan="2"><button type="submit" class="btn btn-info right"> Submit </button></td></tr> </table> </form> {% endblock %} In forms.py: class CalendarGroupsForm(ModelForm): class Meta: model = CalendarGroups fields = ('name',) def __init__(self, *args, **kwargs): super(CalendarGroupsForm, self).__init__(*args, **kwargs) In models.py: class CalendarGroups(models.Model): name = models.CharField(max_length = 155, blank=True, null=True) @property def get_html_url(self): url = reverse('', args=(self.id,)) return f'<a href="{url}"> {self.name} </a>' -
what are the pros and cons of using apache workers when deploying Django in production?
I've been looking at all the various ways to deploy a django project in a windows enviroment, and I came up with an interesting method - I'm now asking if this is a smart way to do it... step 1. Run the django server via cmd python manage.py runserver 8000 step 2. Point an Apache worker to direct incomming traffic to Django I won't pretend to be a networking master, but as long as Apache is the only thing outward facing and able to handle all the security....how insecure can this way be? I can't help but feel like this is cheesing it somehow.... but I'd love to hear any optinions on this! -
Django does not create migration to create index for legacy Foreign Key field
I have a legacy table that does not have an index on the foreign key field in a PostgreSQL database. According to the docs Django automatically creates an index for foreign key fields. I would like to add an index on this field. When I specify db_index=True on the foreign key field and run makemigrations it reports: No changes detected Example: class Member(models.Model): ... group_id = models.ForeignKey(Group, models.DO_NOTHING, db_index=True) # added `db_index=True` here Is there a way to get django to create a migration to create an index for this field? -
Ajax request to changing boolean value of object in django
i'm struggling to make ajax function that change the boolean value of an object without refreshing the page. It returns error 500. Model: class Donation(models.Model): is_taken = models.BooleanField(default=False) HTML: <div style="width: 50%; float:left" class="steps--container"> {% for d in taken %} <div style="width: 80%; float: left"> <h4>{{d.quantity}} bags of {% for c in d.categories.all %} {{c}} {% endfor %} by {{d.user.first_name}} {{d.user.last_name}} </h4> <input type="text" id="donation_id" value={{d.id}} hidden> </div> <div style="width: 20%; float:right"> <input type="button" onclick="updateStatus()" value="{{d.id}}" Mark as not taken> </div> <br> {% endfor %} </div> JS: function updateStatus() { var dId = document.getElementById("donation_id").value; var dIdInt = parseInt(dId, 10) $.ajax({ type: "GET", url: "/ajax/taken_or_not_taken/", data: { "donation_id": dIdInt } }).done(function(e){ console.log("done") console.log(dIdInt) }) .fail(function(e){ console.log('error') console.log(e) }) } View: def taken_or_not_taken(request): obj = request.GET.get('donation_id', '') print(obj) return JsonResponse(obj) Url: url(r'^ajax/taken_or_not_taken/$', views.taken_or_not_taken, name='taken_or_not_taken'), How can i make it works? -
Python Django 3.1 The included URLconf 'mysite.urls' does not appear to have any patterns in it
I'm currently learning django by tutorial. So I changed my return-renders to class-generic in views. in URLs I added as_view() and then it gave me an error. my traceback: File "D:\Anaconda3\lib\threading.py", line 916, in _bootstrap_inner self.run() File "D:\Anaconda3\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "D:\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "D:\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "D:\Anaconda3\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "D:\Anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "D:\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "D:\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "D:\Anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "D:\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf 'mysite.urls' does not appear to have any patterns in it. If you see valid patter ns in the file then the issue is probably caused by a circular import. urls.py: from django.urls import path from . import views app_name = 'myapp' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:id>/', views.DetailView.as_view(), name='detail'), path('<int:id>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] views.py: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from .models import Question from django.template import loader from django.views import …