Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to pass object to a class-based view from a function-based view?
I am trying to define a Django function-based view that will redirect to another class-based view already defined. views.py class DetailView(generic.DetailView): model = Album template_name = 'music/details.html' def albumdelete(request, pk): print(pk) return DetailView.as_view()(request, pk).get_queryset() urls.py (only the relevant part) url(r'^delete/(?P<pk>[0-9]+)/$', views.albumdelete, name='album-delete') Here is the error message I am getting. AttributeError at /music/delete/6/ Generic detail view DetailView must be called with either an object pk or a slug. The actual DetailView is working fine. -
Getting error while deploy django apps in aws elastic beanstalk
[Instance: i-*****************] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 541, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. i'm getting this error, can anyone give some picture of what and why it is coming. -
Django query: Compile __str__() from deeply related models with Many to Many relations
In django admin, I need to bring forth a model name from an __str__() method which gets compiled from the names of multiple deeply related models with Many to Many relations. I am trying to use prefetch_related in the get_queryset() of either the ModelAdmin or the StackedInline class but the queries of the prefetch_related are just added to the already existing ones. Is it possible to achieve such a complicated issue whithout DDoS-ing the database? class DailySchedule(models.Model): hours_keys = models.ManyToManyField(Hour) day = models.Charfield(max...) def __str__(self): return ( '{0}'.format( ','.join( hours.__str__() for hours in self.hours_keys.all() ) ) class PeriodSchedule(models.Model): weekly_schedule_keys = models.ManyToManyField(DailySchedule) period = models.Charfield(...) def __str__(self): return ( '{0}'.format( '&'.join( schedule.__str__() for schedule in self.weekly_schedule_keys.all() ) ) ) class YearlySchedule(models.Model): user = models.OneToOneField(Team) period_keys = models.ManyToManyField(PeriodSchedule) class YearlyScheduleInline(admin.StackedInline): model = YearlySchedule def get_queryset(self, request): ... class TeamAdmin(admin.ModelAdmin): inlines = (YearlyScheduleInline, ) def get_queryset(self, request): ... Using the command line, I figured out that the query that caters for a controlled database hit amount could be the following: q = ( YearlySchedule.objects .prefetch_related('period_keys__weekly_schedule_keys__hours_keys') .all() ) How can I tell django admin to use it effectively? -
Django mai sending error
In my Django website I have a contact form.If the contact form is submitted there need to be send an email to user and admin.When DEBUG is True the email was send. But when DEBUG is False it won'send mail. Here I using DJango mail. -
Difference between tests and interactive shell: files deleted only in the shell
Django 1.11.7 django_cleanup 1.0.1 Django-cleanup deleteы old files on model instance deletion etc. Model: class FileModel(models.Model): file = models.FileField() Currently in MEDIA_ROOT there is a file cache.txt. Just a file. We'll use it in tests. Let's create an instance in the shell: from django.core.files import File file = File(open('/home/michael/PycharmProjects/experiment/media/cache.txt', 'r')) fm = FileModel.objects.create(file=file) In MEDIA_ROOT cache_JO2jFJC.txt appears. Delete it in the shell: fm.delete() (1, {'files.FileModel': 1}) In MEDIA_ROOT cache_JO2jFJC.txt has been deleted. Now there is only cache.txt in MEDIA_ROOT directory. Thefore, django-cleanup works correctly. Let's do the same in a test. And there is a breakpoint put there (have a look at the comment below). class FileTest(TestCase): def test_create_delete(self): file = File(open('/home/michael/PycharmProjects/experiment/media/cache.txt', 'r')) fm = FileModel.objects.create(file=file) fm.delete() # Breakpoint pass At the breakpoint we stop and look around. Aha, the file cache_D9IuGrI.txt appeared in MEDIA_ROOT. Resume. Well, the file is here. It is not deleted. Here is a link to the app: https://github.com/un1t/django-cleanup Direct link to handlers: https://github.com/un1t/django-clean...up/handlers.py Well, handlers listen to signals. Seems logical. How can it be that files are deleted in interactive shell but not in tests? -
Django-mptt admin get child categories
I have next models in my Django project: class Category(MPTTModel): title_of_category = models.CharField(max_length=50, unique=True, verbose_name='Subcategory', default='') parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, default='', verbose_name='Category') class Product(models.Model): category = models.ForeignKey(Category, verbose_name='Category', default='') title = models.CharField(max_length=200, verbose_name='Title of product', default='') Also admin: class CategoryAdmin(DjangoMpttAdmin): list_display = ('title_of_category',) list_filter = ('title_of_category',) admin.site.register(Category, CategoryAdmin) @admin.register(Product) class ProductsAdmin(admin.ModelAdmin): list_display = ('title', ) I would like to show in my admin panel only child category(category without children) in ForeignKey. How can I filter category in admin? -
ManytoMany field in Django admin not appearing
I have a Product model, an Image Model and a Category Model. A Product can have multiple Images(Foreign Key) and a Product can be in multiple Categories a Category can contain multiple Products. A Category can have multiple subcategories(key to itself). class Category(MetaData): parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE) class ProductMetaData): categories = models.ManyToManyField(Category) class ProductImage(models.Model): product = models.ForeignKey(Product, related_name='image', on_delete=models.CASCADE) In Product Django Admin: class ProductDocumentInline(admin.TabularInline): model = ProductDocument class ProductAdmin(MetaData): inlines = [ProductImageInline] fieldsets = ( ('Product Data', { 'fields': ('name', 'short_description', 'description') }), ('SEO', { 'classes': ('collapse',), 'fields': ('meta_title', 'meta_description', 'slug', 'canonical') }), ('MetaData', { 'classes': ('collapse',), 'fields': (('created_at', 'created_by'), ('updated_at', 'updated_by')) }), ) readonly_fields = ('created_at', 'updated_at', 'created_by', 'updated_by') list_display = ('name', 'updated_at') ordering = ('-updated_at',) search_fields = ('name',) admin.site.register(Product, ProductAdmin) admin.site.register(ProductImage) Issues: If I don't customize fieldsets (grouped, ordered) the Categories appear like default in the middle of the form. If there are customized as in my example they don't appear. If they don't appear Products without Categories can be created and I don't want that. I want a product to have at least one category. Now the inline Images appear below all Product fields. I want the Categories to appear first, then … -
Two ModelMultipleChoiceField in one form
When I'm putting two ModelMultipleChoiceField in one form, i have this view: View here As you see, first field is nice, but second is ugly. There are same code (just different data, but even when I duplicate same first field, there are also ugly view of second field). What can be wrong? Code: self.fields['members'] = make_field('Members', members, User.objects.order_by('username')) self.fields['buckets'] = make_field('Buckets', buckets, Buckets.objects.order_by('name'), False) def make_field(label, initial, choices, multi=True): if multi: field = forms.models.ModelMultipleChoiceField(choices, required=False) field.initial_objs = initial field.initial = [ obj.pk for obj in initial ] field.label = label else: field = forms.models.ModelMultipleChoiceField(choices, required=False) field.initial_objs = initial field.initial = [ obj for obj in initial[0].all() ] field.label = label -
How to set session not to expire on browser close in django?
How to set session not to expire on browser close in django? I creates cookie with expiry days 1. In setting.py-> SESSION_EXPIRE_AT_BROWSER_CLOSE = False and SESSION_COOKIE_AGE = 1440 * 60 . When i logged in cookies are created . but the attribute Expires for cookie is ->When the browsing session ends. and sessionid cookies expires on (1 day time)24hours. when i close tab and reopen it , it keeps session continuous. but when i close browser and reopen it the cookies are also deleted even sessionid also.and i comes to login page again. but i wants keep session continuous even after reopening browser. -
How to return actions and parameters in OPTIONS request with django rest framework
I try to return a list of select options for countries using django-countries and django rest framework. I use JWT_AUTH for the authentication. When I try a options request: curl -H "Authentication: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFsYmVydG9fdmVudGEiLCJ1c2VyX2lkIjoyLCJlbWFpbCI6IiIsImV4cCI6MTUwODE2Mzg4Mn0.svxqTThCahSl1Vu27sMjuJyd1PRLk28-Xgn2OKKb5-g" -X OPTIONS -v http://127.0.0.1:8000/api/v1/core/perfilViajeroUserPass/ The response is: {"name":"Perfil Viajero User Pass Create","description":"","renders":["application/json","text/html"],"parses":["application/json","application/x-www-form-urlencoded","multipart/form-data"]} But I think that it should be something like this by default: { "name": "To Do List", "description": "List existing 'To Do' items, or create a new item.", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "note": { "type": "string", "required": false, "read_only": false, "label": "title", "max_length": 100 } } } } Someone could help me? thanks. -
Apache LoadModule issue
my Apache24 cannot load the module Mod_wsgi on Windows , i tried to add the configuration using: mod_wsgi-express module-config and I added the results to the config file: LoadModule wsgi_module "C:/Python27/lib/site-packages/mod_wsgi-4.5.20-py2.7-win-amd64.egg/mod_wsgi/server/mod_wsgiNone" WSGIPythonHome "C:/Python27" but i could not start the Apache Service after that . I have Apache2.4 Python 2.7.14 and on python the following packages: mod-wsgi==4.5.20 Django==1.11.6 setuptools 5.7 -
How to integrate Khalti Payment Gateway in Django/Python?
I am developing a website in Django 1.11. I need to integrate Khalti Payment Gateway. I have followed the [1]: http://docs.khalti.com/. But I'm unable to perform the server side integration with verification api. A step by step procedure would be great. Please Help ! ! ! -
A for loop in forms.py fails to load data immediately after it's sent | Python Django
In the forms.py I have a short piece of code which loads the data, but only after I edit print("hello") in it. The code as follows: models.py: class CreateAssignment(models.Model): user = models.ForeignKey(User, editable=False, blank=True, null=True) progress = models.CharField(max_length=254, editable=False, blank=True, null=True) class SetAssignment(models.Model): mechanic = models.ForeignKey(User, editable=False, blank=True, null=True) assignment = models.IntegerField(blank=True, null=True) The mechanic is a permission, plus this mechanic's ID will show in the url of the website, when you will try to set an assignment for this mechanic. forms.py: class SetAssignmentForm(forms.ModelForm): ASSIGNMENT_CHOICES = () for item in CreateAssignment.objects.all(): if item.progress == 'Scheduling': user = User.objects.get(id=item.user_id).username ASSIGNMENT_CHOICES += ( (item.id, user + ' - ' + str(item.id)), ) assignment = forms.ChoiceField(choices=ASSIGNMENT_CHOICES, help_text='This is the assignment that you want to apply to this mechanic.') class Meta: model = SetAssignment fields = ('assignment', ) The user_id in this situation is the user that has been set in the CreateAssignment model. Now the issue is: - The for loop in the SetAssignmentForm works, but it loads data after I put a print in it or when I remove the print from it. Which of course shouldn't really affect the code. Is there something I'm overlooking? I've been programming in Python Django … -
couldn't register the user in my application
I'm unable to create in it.I couldn't find the mistake.