Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My Django dont show anything
Thank you very much guys! that issue has solved!(Here is my old post Django name 'admin' is not defined ) but it show nothing. I want to show the content in header.html & home.html here is the code personal/views from django.shortcuts import render def index(request): return render(request,'personal/templates/personal/home.html') And here are the code of home and header {% extends "personal/header.html" %} {% block content %} <p> Hey welcome to my very first project by Django :D </p> {% include "personal/includes/"htmlsnippet.html %} {% endblock %} header: <!DOCTYPE html> <!DOCTYPE html> <html lang="en"> <head> <title>Harry-Phuc Coi</title> <meta charset="utf-8"> </head> <body class="body" style="background-color: #f6f6f6f6"> <div> {% block content %} {% endblock %} </div> </body> </html> And here is my path my path -
Deploying Django App on IIS - Secret Key Improperly Configured
I have a Django app deployed on IIS. I am currently working through Django's deployment checklist to secure the app. I have an environment variable with the SECRET_KEY stored as the value. I am accessing the SECRET_KEY with this: SECRET_KEY = os.getenv('SECRET_KEY') print(SECRET_KEY) When I view the IIS hosted app, I get a 500 error. When I use runserver to host the same app, the development server runs with no issues, and the SECRET_KEY is printed out (and is therefore accessed from settings.py). However, this issue occurs when the app is viewed in the browser: ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. How is the SECRET_KEY empty if it's printed out in the command line? -
How to count days belonging to a given month in the range of two Python datetimes?
I have two Python datetime and I want to count the days between those dates, counting ONLY the days belonging to the month I choose. Example: If I have 2017-10-29 & 2017-11-04 and I chose to count the days in October, I get 3 (29, 30 & 31 Oct.). I can't find anything to facilitate the job so I think I'm going to iterate over the days using datetime.timedelta(days=1) and increment a count each time the day belongs to the month I chose. What do you think? Is there a better way to achieve this? I'm using Python 2.7.10 with the Django framework. -
RuntimeError when run my python code
I tried to run my code but I'm faced with this error: File "", line 1, in runfile('C:/Users/niloo/PycharmProjects/untitled/MADRL-master/runners/run_multiwalker.py', wdir='C:/Users/niloo/PycharmProjects/untitled/MADRL-master/runners') File "C:\Users\niloo\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "C:\Users\niloo\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/niloo/PycharmProjects/untitled/MADRL-master/runners/run_multiwalker.py", line 7, in from runners import RunnerParser File "", line 961, in _find_and_load File "", line 946, in _find_and_load_unlocked File "", line 881, in _find_spec File "", line 855, in _find_spec_legacy File "C:\Users\niloo\Anaconda3\lib\site-packages\pyximport\pyximport.py", line 253, in find_module fp, pathname, (ext,mode,ty) = imp.find_module(fullname,package_path) File "C:\Users\niloo\Anaconda3\lib\imp.py", line 269, in find_module raise RuntimeError("'path' must be None or a list, " RuntimeError: 'path' must be None or a list, not What should I do? -
authentication and authorization implementation for web api using saml and token
I am working on project which have following structure- Frontend [client] : angular2 + html Web services [server] : Django Database : mongoDB Currently, I am not using any request authentication or authorization. For SSO authentication I have to use SAML Please suggest me a better and most secure approach to implement from what Currently I have in my mind is - Authenticate client login request against SAML on django side using pysaml generate self encoded token and pass it client for every request authorization I am not much experienced guy but I am learning through reading and mistakes. I didn't found any proper solution for my scenario. It will be big help for me If you have better and most secure approach which should not change technology and tools I am using. Also i am not allowed to use any other database than MongoDB. -
Django: Create multiple objects from one view
I am building a website which allows teachers to ask questions to their students, and get answers back from their students. Each 'review' will consist of a title, description and then a bunch of questions related to the review via a foreign key. The questions would be added one by one and to add more Javascript will be used to add the additional fields. The way I am currently thinking of doing this by having one view, which first processes a form that creates the Review object with the title, description and User that made it. It would then take all the questions the user had entered create an object for each of these using the ID of the review that was just created. I made a simple form and a view that makes the Review block, however I dont know how to go about handling the questions the user wants to add. If there are any other better ways of doing this, please let me know! Thanks -
Django migration slow and resource intensive even with "--fake"
I'm using "DATABASE_ROUTERS" and just added migrations to new database. I have 153 migrations on the "default" database and it seems that all of those have to be run on the new database even though they don't apply. My db router's allow_migrate returns False on every migration except for the one "initial" one related to the new database. I faked that one initial migration and then ran manage.py migrate --database new_database and was surprised that after 45 minutes I had to kill the process when it had used up all the memory and all of the swap space! I then tried again but this time with manage.py migrate --database new_database --fake and it seemed to make no difference. My memory and swap usage went through the roof and I had to again kill the process. All this command should be doing is marking all migrations as completed in the "django_migrations" table. What is really happening to cause so many resources to be used? Am I doing something wrong? What is the best way around this issue? Should I just manually create the "django_migrations" table and then populate it myself? -
Django unittest mock queryset from related object
I have the following function: import unittest from unittest import mock def get_payments(order): return order.payments.filter(status='complete').order_by('-date_added) I want to mock the filter method and the order_by to check the arguments with which are called. I tried: @mock.patch('path.Order.payments.filter.order_by') @mock.patch('path.Order.payments.filter') def test_get_payments(self, mock1, mock2): mock1.assert_called_with(status='complete') mock2.assert_called_with('-date_added') Another mock I tried: @mock.patch('path.Payment.objects.filter.order_by') @mock.patch('path.Payment.objects.filter') @mock.patch('path.Order.payments.objects.filter.order_by') @mock.patch('path.Order.payments.objects.filter') In last two mocks I have an error that path.Order does not exists. I already used a direct mock for a query like Payment.objects.filter() and is working, but starting from a related model like Order I failed. The relationship between Order and Payment is how you would expect, one to many. -
Nested array field with different field types
rankings = ArrayField( ArrayField( models.IntegerField() ) ) This array field will hold an array containing nested arrays each containing IntegerField: [[1,2],[3,4]] Is it possible to have the nested array containing different field types: such as date and integer data: [[2017-11-03 14:23:49.349201+01,2],[2017-11-03 14:23:49.349201+01,4]] ? -
Django append string to field in model
I am trying using legacy, read only DB as django.contrib.auth.models.AbstractBaseUser. Problem is that my legacy password field is SHA1 without starting 'sha1$$' string, just hash only, so I need to append extra string to every password. models.py class Tuzytkownik(AbstractBaseUser): login = models.CharField(db_column='LOGIN', max_length=50, unique=True) haslo = models.CharField(db_column='HASLO', max_length=50) password = 'sha1$$' + haslo USERNAME_FIELD = 'login' REQUIRED_FIELDS = [] Obviously password = 'sha1$$' + haslo not working. How I can acheve it ? To be specyfic - haslo returing 40charts hash like 'cf23df2207d99a74fbe169e3eba035e633b65d94' what I need is 'sha1$$cf23df2207d99a74fbe169e3eba035e633b65d94' -
Django: Best way to merge migrations conflicts
I'm currently working on a dev branch and I will need to merge it to master one day. I have up to 20 migrations files on my dev branch and about the same number on master at the moment. I needed to make migrations on both branches which will result in migrations having the same prefix, (ex 0003_auto) In other words, if you have migrations files generated by makemigrations with the same prefix, what is the best/secure way of handling this. Here are two ways I have figured myself (maybe entirely wrong): Deleting all migrations files, merge the code and then running a fresh makemigrations and migrate which will result in only one migration file. Using the flag --merge flag: makemigrations –merge Now, knowing all this I'd like to know what is the best way of handling this. In general, what should I use that will correctly merge conflicts and get me a fresh version of my project with every model updates. -
HyperlinkedIdentityField an null values in django-rest-framework
I've got two models (code is simplified): class Document(models.Model): data = JSONField() class Item(models.Model): name = models.CharField(max_length=10) doc = models.OneToOneField( Document, blank=True, null=True, on_delete=models.SET_NULL ) I would like to make a hyperlink to the Documents details page in the serializer for Item using the HyperlinkedIdentityField. So I have the URL defined: url(r'^doc/(?P<version>[v1|v2]+)/(?P<pk>[0-9]+)/$', doc_details, name = 'api_document_details' ), And I made the following serializer: class ItemSerializer(serializers.ModelSerializer): doc = serializers.HyperlinkedIdentityField( view_name = 'api_document_details', lookup_field = 'doc_id', lookup_url_kwarg = 'pk' ) class Meta: model = Item fields = ('name', 'doc') The problem here is that the doc field in Item is optional. I got an error as there is no URL to be found if the doc_id = None. Could not resolve URL for hyperlinked relationship using view name "api_document_details". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. I would like HyperlinkedIdentityField to return None (null) if the document is not defined in the record. Does anybody know how to do this? I have tried using the SerializerMethodField() methode in which I use the reverse function and return None if I get an exception, but this has two disadvantages: I … -
AttributeError: '…' object has no attribute '***_set'
I'm trying to display a list of 'stats' assigned to a 'Profile' which extenders the User model. I have a ForeignKey relating the Stat to the Profile. However, i need it to work so the user doesn't have to be logged in so they share progress to users who are not a member of the site. I'm trying to use _set for a backwards relationship on the ForeignKey. I think where it's tripping up is because the 'Stat' model and the 'Profile' models are inside different apps. Would this be causing the issue? Code below: class Stat(models.Model): user = models.ForeignKey(User, default=False) image = CloudinaryField('image', default="thumbnail_mqe6ne", blank=True) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) // Profile view def profile_item(request, id): p = Profile.objects.get(id=7) user_stats = p.stat_set.all() context = { "p": p, "user_stats": user_stats, } return render(request,"profile/profile_share.html", context) The view i'm receiving: 'Profile' object has no attribute 'stat_set' As far as i'm aware using the backwards reference you need to specify the model you are targeting in lowercase. Full stack trace below: Environment: Request Method: GET Request URL: http://localhost:8000/profile/7/ Django Version: 1.10 Python Version: 2.7.14 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'stats', 'home', 'blog', 'challenge', 'haystack', 'ckeditor_uploader', 'ckeditor', 'django_cron', 'anymail', 'templated_email', … -
Easy way to run my containerised Django app?
I have a Django-based web app that has been containerised. I can do a "docker run" it works just fine (does not need any persistent data). Is there any service which will let me just run this container and give me a public URL? Like pushing code to heroku and have it get deployed as a URL? (Can heroku itself do this?) What's the best (=simplest) way to do this? -
Trouble wiring back button with django
Quite new with django and so having difficulties with trying to wire my pages together. I have an Applicant page that has a button to go to a Create Application page. I'm passing it like this: <a class="btn btn-default btn-sm" href="{% url 'applicant:application-new' applicant.pk %}"> <i class="fa fa-file"></i> Create Application </a> From the Create Application page, how do I wire it back to the Applicant page? I've tried doing it this way but I get this error "Reverse for 'applicant-update' with arguments '('',)' not found. " <a class="btn btn-default btn-sm" href="{% url 'applicant:application-new' applicant.pk %}"> <i class="fa fa-fw fa-arrow-circle-left"></i> Back </a> My urls: app_name = 'applicant' urlpatterns = [ url(r'view/(?P<pk>\d+)/$', views.ApplicantUpdate.as_view(), name='applicant-update'), url(r'view/(?P<pk>\d+)/new/$', views.ApplicationCreate.as_view(), name='application-new'), ] View for Create Application: @method_decorator(login_required, name='dispatch') class ApplicationCreate(SuccessMessageMixin, CreateView): form_class = ApplicationForm template_name = 'applicant_application.html' success_message = 'Successfully created application.' I hope you can help me. Thank you very much. -
Django queryset: how to filter a RawSQL annotation based on a queryset field
Is it possible to do something like this in Django: MyModel.objects.annotate( val=RawSQL( "SELECT COUNT(*) FROM another_model_table where some_field= %s", (a_field_from_MyModel) ) ) Thanks! -
Django name 'admin' is not defined
I'm following this tutorial and i have some troubles. https://www.youtube.com/watch?v=3tf8XlhsQAo """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^webapp/', include("webapp.urls")), url(r'^$',include("personal.urls")), ] I've written the code above, however when I executed I get the error below, can anyone help me understand the meaning of this error message? File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\Users\USER\Desktop\Django\mysite\mysite\urls.py", line 24, in <modu > url(r'^$',include("personal.urls")), File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packa s\django\conf\urls\__init__.py", line 52, in include urlconf_module = import_module(urlconf_module) File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\importlib\ init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line … -
ORA-22922: nonexistent LOB value
I created a view that uses WM_CONCAT to group results together, like this: wm_concat(DISTINCT complies) and it runs smoothly in DB, without any errors. But when I try to put it in a Django app, using, models, views, tables it gives me an error ORA-22922: nonexistent LOB value . I tried using listagg(complies, ',') WITHIN GROUP (ORDER BY code) complies, but that gives me a DB error result of string concatenation is too long. I'm aware that WM_CONCAT is not supported by Oracle, but I have used that successfully before. Is this a DB fix or Django fix, and how do you fix it? -
Use LoginRequiredMixin and UserPassesTestMixin at the same time
I want to have a TemplateView Class that uses LoginRequiredMixin and UserPassesTestMixin at the same time. Something like this: from django.views.generic import TemplateView from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin class FinanceOverview(LoginRequiredMixin, UserPassesTestMixin, TemplateMixin): login_url = '/login' redirect_field_name = 'next' def test_func(self): return self.request.user.groups.filter(name="FinanceGrp").exists() def get(self, request, *args, **kwargs): DO SOMETHING IF USER IS AUTHENTICATED AND ALSO MEMBER OF GROUP FinanceGrp Basically as you can see above, what I want to achieve is the following: If user is not authenticated, to redirect user to: https://website/login?next=financeoverview However what I can't figure out is how to redirect users who are authenticated but do not belong to group FinanceGrp to another page. For example: https://website.com/access_denied?previous_page=financeoverview In my case users are always redirected to /login page when they fail the group test. How can I achieve two mixins used at the same time but at the same time both of them are clashing around variable login_url. Unfortunately UserPassesTestMixin is using the same login_url so it makes this trouble for me. Thanks in advance Milos -
Django subquery and annotations with OuterRef
I'm having problems using annotate() with OuterRef in Django 1.11 subqueries. Example models: class A(models.Model): name = models.CharField(max_length=50) class B(models.Model): a = models.ForeignKey(A) Now a query with a subquery (that does not really make any sense but illustrates my problem): A.objects.all().annotate( s=Subquery( B.objects.all().annotate( n=OuterRef('name') ).values('n')[:1] ) ) This gives the following error: Traceback (most recent call last): File "<console>", line 1, in <module> File "myapp/models.py", line 25, in a n=OuterRef('name') File ".virtualenv/lib/python2.7/site-packages/django/db/models/query.py", line 948, in annotate if alias in annotations and annotation.contains_aggregate: AttributeError: 'ResolvedOuterRef' object has no attribute 'contains_aggregate' Is it not possible to annotate a subquery based on an OuterRef? -
Django rest framework allow lookup_field to have several options
I'm currently learning how to build an API for my company. I haven't been doing this for very long at all so I'm basically a junior developer at this point. Following some tutorials, I got my API up and running on a very basic level using class based views. We do scientific measuring with hardware, and it's based off of "runs", "run properties" and "chambers". For the URL, I would like to allow lookups to be based on several different keywords. So if they go to "www.example.com/api/runs_list", the API will show all runs done and chambers for the user that is logged in. I would like to allow search for a specific run, or by chamber. So if they want to go to a run started on 2017-11-02T18:20:24Z they can go to "www.example.com/api/2017-11-02T18:20:24Z" and get the JSON data related to that run. Or if they go to "www.example.com/api/chamber_34-A" they will get all runs performed so far for that chamber. I've looked at lookup_field and lookup_url_kwargs, but it seems to only allow for one option (I have it set to chamber for now). Here is what I have: urls.py from django.conf.urls import url from django.contrib import admin from company.api.views import ( … -
NoReverseMatch thrown in class based view
So I have a view that lists a bunch of links: class CheckpointSelectView(mixins.LoginRequiredMixin, generic.ListView): model = Checkpoint template_name = 'warden/checkpoint_select_view.html' context_object_name = 'checkpoints' A template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% block content %} <ul> {% for checkpoint in checkpoints %} <li><a href="{% url 'checkpoint' checkpoint_name=checkpoint.name %}">{{ checkpoint.name }}</a></li> {% endfor %} </ul> {% endblock %} </body> </html> And some urls: urlpatterns = [ url(r'^$', CheckpointSelectView.as_view(), name='checkpoint_selection'), url(r'^(?P<checkpoint_name>\w+-{0,1}\w+)/$', CheckpointWatchView.as_view(), name='checkpoint'), ] Django throws a NoReverseMatch exception when I navigate to that view, but if I change the template like so: {% block content %} <ul> {% for checkpoint in checkpoints %} <li><a href="{{ checkpoint.name }}">{{ checkpoint.name }}</a></li> {% endfor %} </ul> {% endblock %} it works. Am I using the url tag wrong? Any help is greatly appreciated. -
How to use filter or get method in Django Templats?
I have two tables, document and publishermatter In publishermatter, I have one column FK_doc which is Foreign key of document table. For one document, there are zero or more rows in publishermatter table. I am passing document object to Django Template and and I want row with from publishermatter with specific condition where key(column name) is equal to PAGECSS(value) I am doing in following way. Code 01: <div class="col-sm-7"> {% for item in document.publishermatter_set.key %} {% if item.key == 'PAGECSS' %} <p><br/>{{ item.key }} - {{ item.value }}</p> {% endif %} {% endfor %} </div> Other way is to pass publishermatter from view by doing follwoing doc_obj.publishermatter_set.get(key='PAGECSS') But I want to do this in Template because I am passing documents objects from view. Is there is any way in Django1.4 to filter query on Django template? -
Get record id on the fly after update_or_create
product, created = Product.objects.update_or_create( productid = productid, defaults = { "product_name": row[ 'Product Name' ], "category_name": row[ 'Category Name' ], } ) Right after this I need the django id of the product just created. Is there an efficient way of doing so ? "product" variable doesn't contain the object but only its title. -
django add to cart using ajax adding the same product again
This is my product caraousel. i am trying to add these product to cart using this 'add to cart' button using ajax. so when i click 'add to cart' button it adds the product to the cart,but only the first product, even when i click on second product it still adds again the first product to the cart. My cart look something like this. My product caraousel HTML code is.... <div id="recommended-item-carousel" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="item active"> {% for prod in pro %} <form id="add_to_cart_button"> {% csrf_token %} <div class="col-sm-3"> <div class="product-image-wrapper1"> <div class="single-products"> <div class="productinfo text-center"> <!--sample image, same for all--><img src="{{ prod.image.url }}" alt="" height="150px" width="200px" /> <a href="{% url 'product_info' prod.id %}" > <h2>{{prod.productname}}</h2> </a> <p>{{prod.producttype}}</p> <input type="hidden" id="product_id" value={{prod.id}} /><input type="hidden" id="image" value={{prod.image}} /><input type="hidden" id="productname" value={{prod.productname}} /><input type="hidden" id="price" value={{prod.price}} /><i class="fa fa-shopping-cart"><input class="btn btn-default add-to-cart" type="submit" value="Add to cart"/></i> </div> </div> </div> </div> </form> {% if forloop.counter|divisibleby:4 and not forloop.last %} </div> <div class="item"> {% endif %} {% endfor %} </div> </div> <a class="left recommended-item-control" href="#recommended-item-carousel" data-slide="prev"> <i class="fa fa-angle-left"></i> </a> <a class="right recommended-item-control" href="#recommended-item-carousel" data-slide="next"> <i class="fa fa-angle-right"></i> </a> </div> <!--/recommended_items--> and my cart code is ... <tbody> {% for …