Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pip install Django
I'm trying to install Django on my Linux server. i've installed Python and pip successfully, but i'm getting the ssl error when i ran this pip install Django. pip install Django pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. Collecting Django Could not fetch URL https://pypi.python.org/simple/django/: There was a problem confirming the ssl certificate: Can't connect to HTTPS URL because the SSL module is not available. - skipping Could not find a version that satisfies the requirement Django (from versions: ) No matching distribution found for Django -
How to make POST requests to class-based Views in Django
I have created different class-based views on Django. On the HTML i created some forms make a request with AJAX. My problem is that it gives me Method Not Allowed (POST) I don know if i'm doing it rigth, or if i need to modify something for it to work. My view.py is something like this class Landing(View): def get(self,request): if request.method == 'POST': if request.is_ajax(): data = {"lat":20.586, "lon":-89.530} print request.POST.get('value') return JsonResponse(data) return render(request,'landing.html',{'foo':'bar'}) And i send the reques from Javascript $(document).ready(function() { $('#productos').on('change', function(e) { //Call the POST e.preventDefault(); var csrftoken = getCookie('csrftoken'); var value = $('#productos').val(); $.ajax({ url: window.location.href, type: "POST", data: { csrfmiddlewaretoken : csrftoken, value : value }, success : function(json) { console.log(json); drop(json); }, error : function(xhr,errmsg,err){ console.log(xhr.status+": "+xhr.responseText) } }); }); }); I got some of the code from a web, but i really don't know how to use it, since they used it without class-based views. So, What does need my code to accept the POST method? -
display hierarchy in django
I am using Django to store and display the hierarchy of an organisation. I am struck with displaying the hierarchy of an organisation. For example: Priya (CEO) Harry (Manager) Rekha (Tester) I was able store the hierarchy using a single model and referencing to itself as below: class Emp(models.Model): name=models.CharField(max_length=30) manager=models.ForeignKey('self',null=True,blank=True) designation=models.CharField(max_length=10) def __unicode__(self): return self.name I had an idea to display detail view of each employee when the employee name is clicked but I don't know how to write a view for this and render it to the webpage. Is there a way to directly the hierarchy without using detail view ? Could someone please help. -
How to share a queryset between SerializerMethodFields?
I have a serializer that I use to display details about how a team is performing in a sports league.. class TeamLeagueSerializer(ModelSerializer): class Meta: model = Team fields = [...] games_played = fields.SerializerMethodField() games_won = fields.SerializerMethodField() games_lost = fields.SerializerMethodField() points_for = fields.SerializerMethodField() ...etc... def fixtures(self, team): # Retrieves all relevant fixtures for a given season and a given team return Fixture.objects.filter(Q(home_team=team) | Q(away_team=team), season=self.season) def get_games_won(self, obj): home_results = Q(home_team=obj, result__home_team_score__gt=F('result__away_team_score')) away_results = Q(away_team=obj, result__away_team_score__gt=F('result__home_team_score')) results = self.fixtures(obj).filter(home_results | away_results) return results.count() This all works correctly, but for a league of 8 teams, this can take around 5 seconds to complete since each SerializerMethodField is a separate query being done.. My non-api version of this code is much more simple with a single queryset that annotates each property that this serializer is trying to create, rather than individual queries. So for the given serializer, is it possible to do the same thing and construct a serializers data from a single query instead of multiple? -
Get LIMIT from related Tables
Got code/ context['menu_shop'] = ShopMenu.objects.filter(shop=shop_id) Model: class ShopMenu(models.Model): name = models.CharField(max_length=255, verbose_name=u'Название раздела') shop = models.ForeignKey(Shop, verbose_name=u'Заведение', related_name="menushop") class ShopSubMenu(models.Model): name = models.CharField(max_length=255, verbose_name=u'Название подраздела') shopmenu = models.ForeignKey(ShopMenu, verbose_name=u'Надкаталог', related_name="submenushop") dish = models.ManyToManyField(Dish, blank=True) def __unicode__(self): return u'%s' % (self.name) class Dish........ Whant create vertical paginator but can't understand how get Dish limit So how i can get Dish by LIMIT FROM ShopMenu? \Template: {% for menu in menu_shop %} <h2 class="h1_title">{{ menu }}</h2> <div class="row row-catalog"> {% for submenu in menu.submenushop.all %} {% for dish in submenu.dish.all %} -
Styling XML with XSLT in Wagtail
I am trying to create three sitemaps that are linked from a sitemap index within a Wagtail site. The sitemap index looks like this: <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap> <loc>http://localhost:8000/sitemap-main.xml</loc> </sitemap> <sitemap> <loc>http://localhost:8000/sitemap-education.xml</loc> </sitemap> <sitemap> <loc>http://localhost:8000/sitemap-news.xml</loc> </sitemap> </sitemapindex> The sitemaps are just regular sitemaps like this, for example: <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://localhost:8000/news/lorem-ipsum/</loc> <lastmod>2017-02-17</lastmod> <changefreq>never</changefreq> <priority>0.5</priority> </url> </urlset> My client wants these sitemaps styled in a table-like layout so that it is easier for the user to read, complete with hyperlinks on all the URLs for the user to navigate. My question is how to do this in Wagtail? The sitemaps I have created are using a default template that I did not create, and I'm not sure how to create XSLT files for these, let alone link to them in the template deep within the Wagtail files. Has anyone ever done this before? Any suggestions on how to accomplish this would be great. -
How to implement django-biometric
I am working on a project that requires authentication via biometric. I really don't know where to start. i have done research and i found a package called django-biometrics, but it has no documentation. Is there any better package than django-biometrics (with documentation) or a link to django-biometrics documentation. Thank you. -
Django parsing error on urls
So, im running an example and opening the server keeps returning a parsing error on my uwls page and i cannot seem to fix it. Any help appreciated Error is; File "/Users/Law/Desktop/django/blog/cms/blog/urls.py", line 8 ^ my code is : from django.conf.urls import url from . import views enter code here if i close the bracket for urlpatterns it just erros this instead does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
django action with intermediate page keyerror
I'm newbie in django and I'm doing my first educational project. I would like make an action with an intermediate page, but I receive : KeyError at /admin/students/student/ 'action' Scenario: User selects from "Actions" listbox , action called : u'Перемістити у групу' Presses Go New page should appears with the list of students and listbox to select a group. please explain where is my error. My code is listed below: class UpdateGroupForm(forms.Form): group = forms.ModelChoiceField(queryset=Group.objects.all().order_by('title'), required=False) def update_group(modeladmin,request,queryset): if 'change_group' in request.POST: form=UpdateGroupForm(request.POST) if form.is_valid(): group=form.cleaned_data['group'] updated_group=queryset.update(student_group=group) counter=queryset.count() modeladmin.message_user(request,u"У %s студентів було змненно групу на %s")%(counter,group) return if not form: form= UpdateGroupForm() return (request,'/students/change_group.html',{'students':queryset,'form':form,'title':u'Зміна групи'}) update_group.short_description=u'Перемістити у групу' class StudenAdmin(admin.ModelAdmin): action_form = UpdateGroupForm actions = [update_group] list_display = ['last_name','first_name' ,'ticket','student_group'] list_display_links = ['last_name','first_name'] list_editable = ['student_group'] ordering = ['last_name'] list_filter = ['student_group'] list_per_page = 10 search_fields = ['last_name','first_name' ,'ticket','notes'] def get_view_on_site_url(self, obj): return reverse ('students_edit',kwargs={'pk':obj.id}) -
How I can use class-based view in ViewSet?
I have a ViewSet: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer And appropriate urls: from .users.api.views import UserViewSet router = routers.DefaultRouter() router.register('users', UserViewSet, 'user') urlpatterns = [ url(r'^v1/', include(router.urls)), ] It works, but I want to add username-password authentification to UserViewSet: @list_route(methods=['post'], permission_classes=[AllowAny]) def login(self, request): #check login and password #creare and return token Of cource I can write It by my-self, but I interest, how I can use rest_framework.authtoken.views.ObtainAuthToken for my goals. Thanks for help! -
Select option not working for Modal
Can someone help clarify here? I am trying to do the same thing as this post but set the value dynamically. However when I do this, even though I'm setting the values before opening the modal, the value does not seem to be getting set. I have a Create New Campaign button as part of a table which when clicked, calls the javascript methods shown below: <th data-field="create_campaign"><span class="create_campaign" text="{{product.id}}"><a class="" href="#" data-target="campaign_modal" value="{{product.id}}">create new campaign</a></span><br></th> HTML <div id="campaign_modal" class="modal"> <div class="modal-content"> <blockquote> Product Campaign </blockquote> <div id="" class="row"> <div class="input-field col s5"> <select id="product_selector" name="product_selector"> <option disable value=" ">Select a Product </option> {% for product in all_org_products %} <option value="{{product.id}}">{{product.name}}</option> {% endfor %} </select> </div> <div class="input-field col s5"> <input type="text" id="campaign" class=""/> <label for="campaign" id="label_campaign"> Campaign </label> </div> <div class="input-field col s2"> <a class="btn-floating btn-small waves-effect waves-light teal" onclick="submitCampaign()"><i class="material-icons">add</i></a> </div> </div> <div class=" center"> <span class="done_btn"><button id="done_btn" class="btn blue waves-effect waves-light modal-action"><i class="material-icons left" >done</i>Done</button></span> </div> </div> </div> Javascript $('.create_campaign').click(function () { product_id = $(this).attr('text'); var product_select = document.getElementById('product_selector'); console.log(product_select); var index=0; for (var i=0; i<product_select.options.length; i++){ if (product_select.options[i].value == product_id){ index=i; product_select.value=product_id break; } } product_select.selectedIndex = index; openCampaignModal(); }); function openCampaignModal(){ $('#campaign_modal').openModal(); }; -
Incorporating Django's system checks into unit test suite?
I recently deployed some broken code to our staging environment. The new code failed Django's system checks (error messages reproduced below, though this question is more general). Our unit test suite ran cleanly. My question is this: what is the right way to ensure that system checks get run before code can be deployed? Initially I guessed that the tests were able to run without performing system checks because we use pytest instead of Django's test runner. However, adding a simple test and invoking manage.py test showed that the Django test runner also runs without performing system checks. One idea I had is to run the manage.py check command in our build pipeline, and fail the build on a nonzero return value. A downside of this approach is that it'd introduce another developer step before code could be committed (e.g. remember to run manage.py check in addition to running the unit test suite). Another idea is to add a unit test that runs the system checks. This seems technically feasible, but is it consistent with the purpose and design of Django's system check framework? I note that the documentation has a section on writing tests for custom checks, which doesn't … -
Bokeh Error Error rendering Bokeh model: could not find tag with id: 3f5f37a7-a9cb-458c-be6e-a8a56438d4f9
I am using Bokeh with the Django framework. I use Bokeh's charts package to display pandas dataframe. I have a list of data already loaded within my python object. `Class Cake_Machine(): ingredient=['sugar','strawberry'] def makecake(self, ingredient=ingredient): df=pandas.csv_read(path = ingredient.txt) ingredient_list = Line(df, legend = 'top_right') weights = df[2] return [ingredient_list, weights] Although the line chart displays fine when the page is pre-populated, any input on the form field from html returns Bokeh Error Error rendering Bokeh model: could not find tag with id: 3f5f37a7-a9cb-458c-be6e-a8a56438d4f9 The forms work fine as the weight output shows on the html template. Anyone with experience using Bokeh with similar problems? -
Not able to bring in static files in Django
I've looked up various solutions and tutorials but nothing seems to bring the static files when i do the "python manage.py collectstatic" command Heres my settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIR = ( os.path.join(BASE_DIR,'..','static'), #os.path.join(BASE_DIR,'..','static','css'), os.path.join(BASE_DIR,'static'), #('assets',os.path.join(BASE_DIR,'static')), ) STATIC_ROOT = os.path.join(BASE_DIR,'static') I think if everything goes well it must also bring the files from my css and images folder which are in my static folder , Which is in my BASE_DIR. But instead it copies all admin files but not my static files Type 'yes' to continue, or 'no' to cancel: yes Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\css\base.css' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\css\changelists.css' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\css\dashboard.css' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\css\fonts.css' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\css\forms.css' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\css\login.css' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\css\rtl.css' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\css\widgets.css' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\fonts\LICENSE.txt' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\fonts\README.txt' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\fonts\Roboto-Bold-webfont.woff' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\fonts\Roboto-Light-webfont.woff' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\fonts\Roboto-Regular-webfont.woff' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\calendar-icons.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\icon-addlink.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\icon-alert.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\icon-calendar.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\icon-changelink.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\icon-clock.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\icon-deletelink.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\icon-no.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\icon-unknown-alt.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\icon-unknown.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\icon-yes.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\inline-delete.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\LICENSE' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\README.txt' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\search.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\selector-icons.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\sorting-icons.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\tooltag-add.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\tooltag-arrowright.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\gis\move_vertex_off.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\img\gis\move_vertex_on.svg' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\actions.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\actions.min.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\calendar.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\cancel.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\change_form.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\collapse.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\collapse.min.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\core.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\inlines.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\inlines.min.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\jquery.init.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\popup_response.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\prepopulate.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\prepopulate.min.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\prepopulate_init.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\SelectBox.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\SelectFilter2.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\timeparse.js' Copying 'C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\static\admin\js\urlify.js' … -
Python. Django test weird behavior. PDB
So, I have a test that looks like this: for retailer in Retailer.objects.all(): retailer_categories = retailer.categories.all() empty_categories = [] not_empty_categories = [] for category in retailer_categories: if StockItem.objects.filter(retailer=retailer, product__category=category).exists(): not_empty_categories.append(category.name) else: empty_categories.append(category.name) response = self.client.get(reverse("misuper:retailer_categories", kwargs={"id": retailer.id})) self.assertEqual(response.status_code, status.HTTP_200_OK) response_category_names = [c["name"] for c in response.json()] for category_name in response_category_names: pdb.set_trace() # HERE self.assertEqual(category_name in not_empty_categories, True, "%s not in %s" % (category_name, not_empty_categories)) # THIS TEST The weird part is that if I run the test and at the breakpoint I just hit c (continue), it fails the test: /home/alejandro/Proyectos/misuper_env/misuper_project/app/misuper/tests.py(1162)test_retailers_categories() -> pdb.set_trace() (Pdb) c FAIL ... AssertionError: Bebidas not in [] But if in the breakpoint I write category_name and response_category_names just to print them, the test passes correctly. (Pdb) category_name u'Bebidas' (Pdb) response_category_names [u'Bebidas'] (Pdb) c ok Why?? -
How make conditional expression on Django with default value of object?
See https://docs.djangoproject.com/en/dev/ref/models/conditional-expressions/ conditional expression with Case; o = Object.annotate( custom_price=Case( When(price=1, then=Value(2)), default=0, output_field=DecimalField(), ) ) How use set 'default' - current value of Object? Now it writed only as const: 0 Want something like: if price =1: custom_price = 2 else: custom_price = Object.price -
Send large files throug http with httpie
I recently discovered httpie (https://httpie.org) and liked it a lot. it's very simple to make requests for a remote server, specially when working with REST API requests. But now I'm stucked with sending large files with httpie. It first charge the entire file to memory so if file is too large, I get Memory Error: http: error: Memory Error: The command that generates this error is: $ http -f POST www.example.com/upload/ field@file.raw So anyone knows if there is a way to send large files in chunks with httpie? At least in official documentation I didn't found anything. -
Sending notification to GCM from Django via FCM token
I am doing my first steps in Django-Android interaction, and I am bit confused about the logic how FCM technology works. I have installed django-fcm via pip, and now my goal is to send a notification to Android device via FCM token that has been sent to server by Android device via REST resource. The third-party Android developers tell that they would give me only the FCM token and I should be able to send a notification. And I'm a bit confused by the following code snippet from the doc devices = FCMDevice.objects.all() What is FCM device ? And how does JSON code in the example: { "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", "notification" : { "body" : "great match!", "title" : "Portugal vs. Denmark", "icon" : "myicon" } } ...related to this: device = FCMDevice.objects.all().first() device.send_message("Title", "Message") device.send_message(data={"test": "test"}) device.send_message(title="Title", body="Message", icon=..., data={"test": "test"}) THE QUESTION IS what is the minimum code snippet to send the simplest notification to an Android device identified by its FCM token -
Django - adding arbitrary custom attributes to the request object (without touching/modifying builtin ones)
There are a number of answers here* indicating that it is a bad idea to modify the request, but they all seem to concern existing META/HTTP attributes or the built-in Django ones. I am guessing that's because that risks interfering with Django/middlewares/whatever Apache/nginx is fronting and there are better ways. What are the potential risks if you add attributes that only have significance to your own code? For example, during development, I use pdb.set_trace() quite a lot to stop processing, especially on exceptions. And I already use conditionals to guard them, like if USE_PDB: pdb.set_trace(). So, I thought that, if I append ?pdb=1 to the url, then I can dynamically tell my code that it should halt. Something like, perhaps through middleware, request.USE_PDB = bool(int(request.GET["pdb"])), which I could then test later. Yes, I know forgotten debugger halts sitting on a live server are a mess, but I am only concerned about risks to built-in Django behavior here, not to my code. Existing questions * django modifying the request object Django: creating/modifying the request object -
NoReverse Match in Mezzanine - I am using get_absolute_url for slug field
I am currently developing a mezzanine project. I always get "NoReverseMatch": Reverse for 'download' with arguments '()' and keyword arguments '{u'slug': u'read-metxt-1-2-3-4-5-6-7-8-9-10'}' not found. 0 pattern(s) tried: [] In my previous app before I used Mezzanine, there was no error. I just copy-pasted the code and modify it accordingly. Sorry for asking the same question. I know there are other similar questions as mine, but none of them is working. models.py from __future__ import unicode_literals from django.db import models from django.core.urlresolvers import reverse from django.db.models.signals import pre_save from django.utils.text import slugify import os # Create your models here. class ReportOutline_File(models.Model): slug = models.SlugField(unique=True, max_length=100) report_outline = models.FileField() def get_absolute_url(self): return reverse('txttoppt: download', kwargs={"slug": self.slug}) def create_slug(instance, new_slug=None): slug = slugify(instance.report_outline.name) #slugifying the title if new_slug is not None: slug = new_slug qs = ReportOutline_File.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) print instance.slug pre_save.connect(pre_save_post_receiver, sender=ReportOutline_File) urls.py (main: mezzanine) urlpatterns += [ url("^$", direct_to_template, {"template": "index.html"}, name="home"), url("^convert-to-ppt/", include("toppt.urls", namespace="txttoppt")),] urls.py (app) from .views import ( converttexttoppt_func, download ) urlpatterns = [ url(r"^", converttexttoppt_func, name="converttexttoppt"), url(r"^download/(?P<slug>[\w-]+)/$", download, name='download')] views.py def converttexttoppt_func(request): form … -
Internal Server Error 500 Apache 2.4 and mod_wsgi
From my apache error log I'm getting the following output: [Fri Feb 24 18:44:44.617451 2017] [mpm_winnt:notice] [pid 16752:tid 684] AH00354: Child: Starting 64 worker threads. [Fri Feb 24 18:44:49.932581 2017] [wsgi:error] [pid 16752:tid 1232] [client ::1:51965] mod_wsgi (pid=16752): Target WSGI script 'C:/Users/Rasmus/workspace/MainSite/src/MainSite/wsgi.py' cannot be loaded as Python module. [Fri Feb 24 18:44:49.932581 2017] [wsgi:error] [pid 16752:tid 1232] [client ::1:51965] mod_wsgi (pid=16752): Exception occurred processing WSGI script 'C:/Users/Rasmus/workspace/MainSite/src/MainSite/wsgi.py'. [Fri Feb 24 18:44:49.945590 2017] [wsgi:error] [pid 16752:tid 1232] [client ::1:51965] Traceback (most recent call last):\r [Fri Feb 24 18:44:49.945590 2017] [wsgi:error] [pid 16752:tid 1232] [client ::1:51965] File "C:/Users/Rasmus/workspace/MainSite/src/MainSite/wsgi.py", line 16, in <module>\r [Fri Feb 24 18:44:49.945590 2017] [wsgi:error] [pid 16752:tid 1232] [client ::1:51965] application = get_wsgi_application()\r [Fri Feb 24 18:44:49.945590 2017] [wsgi:error] [pid 16752:tid 1232] [client ::1:51965] File "c:\\anaconda3\\lib\\site-packages\\django\\core\\wsgi.py", line 13, in get_wsgi_application\r [Fri Feb 24 18:44:49.945590 2017] [wsgi:error] [pid 16752:tid 1232] [client ::1:51965] django.setup()\r [Fri Feb 24 18:44:49.945590 2017] [wsgi:error] [pid 16752:tid 1232] [client ::1:51965] File "c:\\anaconda3\\lib\\site-packages\\django\\__init__.py", line 17, in setup\r [Fri Feb 24 18:44:49.945590 2017] [wsgi:error] [pid 16752:tid 1232] [client ::1:51965] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)\r [Fri Feb 24 18:44:49.945590 2017] [wsgi:error] [pid 16752:tid 1232] [client ::1:51965] File "c:\\anaconda3\\lib\\site-packages\\django\\conf\\__init__.py", line 55, in __getattr__\r [Fri Feb 24 18:44:49.945590 2017] [wsgi:error] [pid 16752:tid 1232] [client … -
saving image/doc or media files dynamicallly created folder from input form in django
I want to make a Notes Platform where teachers can upload Notes and others can access it . The problem is whenever I am uploading the image it is going to the same folder and I am not able to categorise it according to year,branch,subject, and unit-wise. Since all the media files are uploaded to the same folder I am unable to get the logic how will i able to fetch the media/image/doc file when a user query for the notes. my model form is :- class Note(models.Model): year_choices = ( ( 1 , 'First' ), ( 2 , 'Second'), ( 3 , 'Third' ), ( 4 , 'Fourth') ) branch_choices = ( ( 'IT','IT' ), ( 'EE','EE' ), ( 'CSE','CSE'), ( 'EC','EC' ), ( 'ME','ME' ), ( 'CE','CE' ), ) unit_choices = ((1,'1'),(2,'2'),(3,'3'),(4,'4'),(5,'5'), (6,'6'),(7,'7'),(8,'8'),(9,'9'),(10,'10')) branch = models.CharField(max_length=55,choices=branch_choices) year = models.IntegerField(choices = year_choices) subject_name = models.CharField(max_length = 15) unit = models.IntegerField(choices=unit_choices) location = 'images' picture = models.ImageField(upload_to = location) My notes uploading form and searchform(for searching) is field is :- class notesform(forms.ModelForm): class Meta: model = Note fields = [ 'year','branch','subject_name','unit','picture' ] class searchform(forms.ModelForm): class Meta: model = Note fields = [ 'year','branch','subject_name','unit' ] My notes adding function logic is … -
determine if Django model is marked for deletion
My example is very contrived, but hopefully it gets the point across. Say I have two models like this: class Group(models.Model): name = models.CharField(max_length=50) class Member(models.Model): name = models.CharField(max_length=50) group = models.ForeignKey(Group) I want to add some code so that when a Member is deleted it gets recreated as a new entry (remember, very contrived!). So I do this: @receiver(post_delete, sender=Member) def member_delete(sender, instance, **kwargs): instance.pk = None instance.save() This works perfectly fine for when a Member is deleted. The issue, though, is if a Group is deleted this same handler is called. The Member is re-created with a reference to the Group and an IntegrityError is thrown when the final commit occurs. Is there any way within the signal handler to determine that Group is being deleted? What I've tried: The sender seems to always be Member regardless. I can't seem to find anything on instance.group to indicate a delete. Even trying to do a Group.objects.filter(id=instance.group_id).exists() returns true. It may be that the actual delete of the parent occurs after post_delete calls occur on the children, in which case what I'm trying to do is impossible. -
Django how to filter queryset based on nested many to many relations in one query
Let's say I have a product that can have various child products, and the models are defined like this class Country(models.Model): name = models.CharField() class Product(models.Model): parent = models.ForeignKey( 'self', null=True, blank=True, related_name='children') name = models.CharField() countries = models.ManyToManyField(Country) my goal is to retrieve all products that have one or more child products that are linked to a specific country. In my use case I need this information as a Queryset. What I have tried is this and it works: valid_products = [] desired_country = Country.objects.get(name='mycountry') for product in Product.objects.all(): for child in product.children.all(): countries = child.countries.all() for country in countries: if country == desired_country: valid_products.append(product.id) desired_queryset = Product.objects.filter(pk__in=valid_products) This method requires and additional query to convert my result into a queryset and I would like to avoid that. Is it possible to filter a queryset like this directly with the Django ORM? -
ModuleNotFoundError: No module named 'forms'
New to django, I am trying to understand this error. The forms is in the folder of the project. My forms.py is importing from django forms. class LoginForm(forms.Form): email = forms.EmailField(label='Courriel') password = forms.CharField(label='Mot de passe', widget = forms.PasswordInput) My views.py is importing LoginForm I don't know why I am getting this error? Thanks