Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cms content getting published in draft mode
I have installed djangocms-snippet and using placeholder in my template as shown in image I have included placeholder on template page like {% block content %} {% placeholder "Articles" %} {% endblock content %} Issue: whenever I am updating snippet for e.g. news and changing content and then saving its getting reflected automatically in live version without having clicked "publish page changes".Ideally it should only be reflected to the logged in user and after verifying changes are correct I can publish but as soon as i am changing content and saving its getting reflected on live page.Live refers to staging environment here. -
Reverse not found
I'm using Django 1.7 and I have this URL pattern: url(r'^account/unsubscribe/(?P<user_id>[^/.]+)/(?P<token>[\w.:\-_=]+)$', views.unsubscribe, name='account-unsubscribe') And I have this in my project code: def create_unsubscribe_link(self): email, token = self.user.email_notifications.make_token().split(":", 1) user_id = TelespineUser.objects.get(email=email) return reverse('account-unsubscribe', kwargs={'user_id': user_id, 'token': token, }) Why do I get this while calling create_unsubscribe_link?: NoReverseMatch: Reverse for 'account-unsubscribe' with arguments '()' and keyword arguments '{'token': '1ehbA0:czK8xR8IGiGu7WdEuYRkYigXBzI', 'user_id': <TelespineUser: name: demo@telespine.com, id: 1>}' not found. 1 pattern(s) tried: ['api/v1/account/unsubscribe/(?P<user_id>[^/.]+)/(?P<token>[\\w.:\\-_=]+)$'] -
Can you tell me how to Start django project in pydroid2?
I am using pydroid 2 in my android to learn python and couldnot figure how start a django project. I have already installed django -
SocialApp matching query does not exist
I m getting this error as soon as I m clicking on sign up href link. I m unable to figure out what's the problem if someone can help me out I would really appreciate that : Error DoesNotExist at /accounts/github/login/ SocialApp matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/accounts/github/login/ Django Version: 1.8.7 Exception Type: DoesNotExist Exception Value: SocialApp matching query does not exist. Exception Location: /usr/lib/python2.7/dist-packages/django/db/models/query.py in get, line 334 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/vaibhav/Desktop/projects/food_orders', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/vaibhav/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/gtk-2.0'] Server time: Fri, 2 Feb 2018 18:41:48 +0000 My settings.py looks like this : # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'restaurants', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.github', ) SITE_ID = 2 # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) LOGIN_REDIRECT_URL = 'home' ACCOUNT_EMAIL_VERIFICATION = 'none' My views.py … -
How to display contact form on landing page in Django
I have a little answer. Like in the subject. I have a landing page and all of hrefs to another pages looks like this <article id="kontakt"> and the link from menu looks like this <li><a href="#kontakt">Kontakt</a></li> I've created a newapp names kontakt witch include: forms.py from django import forms class WyslijEmail(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(required=True,widget=forms.Textarea) views.py from django.shortcuts import render, redirect from django.core.mail import send_mail from .forms import WyslijEmail def kontakt(request): sent = False if request.method == 'POST': form = WyslijEmail(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] send_mail(subject, message, from_email,['my@mail.com']) sent = True else: form = WyslijEmail() return render(request,'strona/index.html', {'form':form, 'sent': sent}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.kontakt, name='kontakt'), ] And on the end I have a html code : <article id="kontakt"> <h2 class="major">Kontakt</h2> {% if sent %} <h4>Wiadomość została wysłana</h4> {% else %} <form action="." method="post" name="kontakt"> {% csrf_token %} {{ form.as_p }} <p><input type="submit" value="Wyślij wiadomość"></p> </form> {% endif %} The result is that, when I runserver and clik on the mainpage in link 'Kontakt', the javascript opened me a window with kontakt but displaying me only a table with … -
Python unit test : Why need `mock` in a test?
I can not understand why we need mock in some test cases, especially like below: main.py import requests class Blog: def __init__(self, name): self.name = name def posts(self): response = requests.get("https://jsonplaceholder.typicode.com/posts") return response.json() def __repr__(self): return '<Blog: {}>'.format(self.name) test.py import main from unittest import TestCase from unittest.mock import patch class TestBlog(TestCase): @patch('main.Blog') def test_blog_posts(self, MockBlog): blog = MockBlog() blog.posts.return_value = [ { 'userId': 1, 'id': 1, 'title': 'Test Title, 'body': 'Far out in the uncharted backwaters of the unfashionable end of the western spiral arm of the Galaxy\ lies a small unregarded yellow sun.' } ] response = blog.posts() self.assertIsNotNone(response) self.assertIsInstance(response[0], dict) This code is from this blog. What I'm curious about is that as you can see in test code, test code set blog.posts.return_value as some desirable object(dict). But, I think this kind of mocking is useless because this code just test How well the user set the return_value correctly in the test code, not what the real Blog' object really return. What I mean is, even if I make real posts function return 1 or a in main.py, this test code would pass all the tests because the user set the return_value correctly in the test code! Can … -
How to serve a view at every URL endpoint
The reason for my wanting to serve the same view at every URL endpoint, is because the view sends Notification information to the authenticated user. For example, here is the view which has data that I would like served in every page: class NotificationsView(View): def get(self, request, *args, **kwargs): profile = Profile.objects.get(user__username=self.request.user) notifs = profile.user.notifications.unread() return render(request, 'base.html', {'notifs': notifs}) I'm trying to send the context variables into my template to be used with javascript. The JS file lives apart from the template, so I'm attempting to declare the global JS vars in the base template first, then use them in the JS file. base.html: ... {% include "landing/notifications.html" %} <script src="{% static 'js/notify.js' %}" type="text/javascript"></script> {% register_notify_callbacks callbacks='fill_notification_list, fill_notification_badge' %} landing/notifications.html: <script type="text/javascript"> var myuser = '{{request.user}}'; var notifications = '{{notifs}}'; </script> notify.js: ... return '<li><a href="/">' + myuser + notifications + '</a></li>'; }).join('') } } Based on this code, you can see how I've ended up in a predicament where I need to use the CBV to send the proper notifications to the landing/notifications.html in order to make sure the javascript variables can be dynamically rendered for the JS file. I am utterly confused as to how the … -
How can I change the checkbox button in django admin to toggle switch button?
I am trying to customize the django admin section and want to change the checkbox of a model attribute (BooleanField) into a toggle switch. -
Django httpresponse returns corrupted file
I'm trying to deploy a Django application i just got handover from an ex-colleague to a server on my network, the application runs perfectly on my laptop with python manage.py runserver I took the application and set up the environment on the server and ran the app there it works fine but there is this part where i return a XLSM file format to the user using HTTPresponse but it returns a corrupted file, the code already saves a copy of the file to be returned in the app folder and this file is fine and not corrupted, also when i compared the two files i found the correct file size is 93 KB but the corrupted returned file is 269 B. The part of the code which returns to the user the file is as follows excel_file = BytesIO() writer = pd.ExcelWriter(excel_file, engine='xlsxwriter') #result_final is the file i save on the hard disk result_final.to_excel(writer, sheet_name='Summary Report') workbook = writer.book my_worksheets = {} for worksheet in workbook.worksheets(): my_worksheets[worksheet.get_name()] = worksheet worksheet = my_worksheets['Summary Report'] workbook.add_vba_project('./vbaProject.bin') worksheet.insert_button('E3', {'macro': 'Macro5', 'caption': 'Load Charts', 'width': 70, 'height': 70}) writer.save() workbook.close() excel_file.seek(0) response = HttpResponse(excel_file.read(), content_type='application/vnd.ms-excel.sheet.macroEnabled.12') response['Content-Disposition'] = 'attachment; filename=Summary Report.xlsm' return response This … -
when to use "/" (project/app/model) and when to use dotted path (project.apps.models) in django
Can someone explain the logic and reason when to use the dotted path and when to use the path with slash("/") in django ? When we write path in terminal it is python manage.py test project.apps.tests but when it is written in code (templates etc) its like projects/apps/directory. I didnt find any related question. If this question is already asked please provide the link. -
Django: text search: Haystack vs postgres full text search
I am using Django 2.0 I have posts with title and description. For the first time i am trying to implement search functionality. I found after searching the following options: Haystack and postgres full text search (https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/search/) Which is the suggested one to work with. -
django: full text search for sqlite database
I am using Django 2.0. I have a list of posts with a title and descrption. I have found the full text search documentation for postgres database at https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/search/. I am presently using sqlite database. I there any documentation for sqlite database full text search in Django. -
In Django test there is empty queryset when assigned to variable but not empty when printed in console during debug
I'm debugging Django (1.11.8) test and observing strange behavior: when stopped in debugger and switched to Ipython console typing: Model.objects.all() returns non-empty Queryset. However, when the same expressions is assigned to variable e.g.: obj_qs = Model.objects.all() then obj_qs is empty Queryset. I would expect the same result from both statements. Am I missing something important in tests setup? I'm using both setUpTest() and setUp() methods to initialize objects for the test. -
Send Json string from javascript in chrome extension to django
I am working on a chrome extension where I have a simple form when we click on a extension icon. This form data has been converted into JSON string. This was fine and working correctly.I want to send this JSON string from java script which is in chrome extension to Django and thereby I have to store Json data in Mysql database. popup.js: document.addEventListener('DOMContentLoaded', documentEvents, false); function myAction(fname,femail,fpassword) { var json={ "email":fname.value, "name":femail.value, "password":fpassword.value }; var html = JSON.stringify(json); alert(html); /*var json_obj = document.getElementById('output'); json_obj.value=html;*/ var xmlhttp = new XMLHttpRequest(); var theUrl = "http://127.0.0.1:8000/music/"; xmlhttp.open("POST", theUrl, true); xmlhttp.onreadystatechange = function() { alert(xmlhttp.readyState + " " + xmlhttp.status); if (xmlhttp.readyState == 4){ alert("entered"); } else{ alert("not entered"); } }; xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); xmlhttp.send(html); } function documentEvents() { var submitButton = document.getElementById('submit') submitButton.addEventListener('click', function(event) { var formId = document.getElementById('test'); var name = document.getElementById('name'); var email = document.getElementById('email'); var password = document.getElementById('password'); myAction(name,email,password); }); } popup.html <!DOCTYPE html> <html> <head> <title>Wonderful Extension</title> <script src="popup.js"></script> </head> <body> <div style="padding: 20px 20px 20px 20px;"> <h3>Hello,</h3> <p>Please enter your name : </p> <form id="test" action="#" method="post"> <div class="form-group"> <label for="email">Email</label> <input class="form-control" type="text" name="Email" id="email" /> </div> <div class="form-group"> <label for="name">Name</label> <input class="form-control" type="text" name="Name" id="name" /> </div> … -
Writing multiple page pdf from html template using weasy print and django
Hi am generating PDF's from html template containing a table which number of rows vary, problem is when the rows are in excess of certain number(12) the rest of the rows plus the footer are pushed further below and don't appear in the generated pdf.How can I make it dynamic so that extra info is pushed to new page each having atleast a certain number of rows, or is there a way weasy print to move data to another page if the current is full So far I have page breaks on the template but it has worked. {% for record in data %} <tr> <td> {{ record.id}}</td> <td> {{ record.date}}</td> </tr> {% if forloop.counter|divisibleby:12 %} <div style="page-break-after: always;"></div> div style="page-break-before: always;"></div> {% endif %} {% endfor %} -
How to allow page refresh/redirect after Ajax POST submission (of Django form)
I'm a client-side newbie learning the ropes, and need to clarify Ajax concepts. e.preventDefault(); is a typical method of preventing form submission (page refresh) in JS. One use case where the above is handy is Ajax-based form submission. Sample code is: function overwrite_default_submit(e) { // block the default behavior e.preventDefault(); // create and populate the form with data var form_data = new FormData(); form_data.append("reply", text_field.value); // send the form via AJAX var xhr = new XMLHttpRequest(); xhr.open('POST', e.target.action); xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken')); xhr.send(form_data); } I have two questions: 1) Imagine the POST request is being sent to a function that ends with a redirect to a different URL. For example, I use Django to develop web applications; a typical Django view may end up with return redirect("home") where home is the home page of the said app. In such a scenario, how does preventDefault() prevent the redirect statement in server-side code from executing? I'm trying to understand the exact mechanics behind it. 2) What if one wanted page refresh (or redirect) to proceed normally after an Ajax POST request? What tweaks need to be made? Would love to see an illustrative example to clarify my concepts. I'm well-versed in Django (Python) so … -
In ModelSerializer self.context doesn't have request , how to get this
my serialiser class is: class NakshatraDateSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) is_note_present = serializers.SerializerMethodField(read_only=True) def get_is_note_present(self, nakshatra_date ): user = None request = self.context.get("request") print (str(request)) if request and hasattr(request, "user"): user = request.user # user = serializers.SerializerMethodField('_user') if user is None: logging.error("user is none") return False try: nakshatra_date_note = Notes.objects.all().get(nakshatra_date=nakshatra_date, created_by=user) except ObjectDoesNotExist: nakshatra_date_note = None if nakshatra_date_note is None: logging.error("no note present for this nakshatra date") return False logging.error(str(nakshatra_date_note)) return True vewclass is : class NakshatraDateViewSet(viewsets.ModelViewSet): """ Nakshatra dates """ permission_classes = (AllowAny,) queryset = NakshatraDate.objects.all() serializer_class = NakshatraDateSerializer() pagination_class = LargeResultsSetPagination filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) filter_class = NakshatraDateFilter def filter_queryset(self, queryset): queryset = super(NakshatraDateViewSet, self).filter_queryset(queryset) return queryset.order_by('-id') def perform_create(self, serializer): serializer.save() i am trying to set value 'True' in variable is_note_present if a Note is present on a particular date. or else 'False'. But i am not able to get request object in self.context. class Notes(models.Model): date = models.DateField(null=False) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True, editable=False) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='notes', on_delete=models.CASCADE) -
Context variables not resolving under template inheritance using global javascript vars
I'm trying to send context variables into my template to be used with javascript. The JS file lives apart from the template, so I'm attempting to declare the global JS vars in the base template first, then use them in the JS file. One of the variables works(myuser), but the other does not(notifications). What's going on? views.py: class NotificationsView(View): def get(self, request, *args, **kwargs): profile = Profile.objects.get(user__username=self.request.user) notifs = profile.notifications.unread() return render(request, 'base.html', {'notifs': notifs}) base.html: ... {% include "landing/notifications.html" %} <script src="{% static 'js/notify.js' %}" type="text/javascript"></script> {% register_notify_callbacks callbacks='fill_notification_list, fill_notification_badge' %} landing/notifications.html: <script type="text/javascript"> var myuser = '{{request.user}}'; var notifications = '{{notifs}}'; </script> notify.js: ... return '<li><a href="/">' + myuser + notifications + '</a></li>'; }).join('') } } -
i am using Centos6.9 and if I run the command$python manage.py runserver in get the below error
(djangoenv)[rapidbox@instance-1 trusource]$ python manage.py runserver Unhandled exception in thread started by <function wrapper at 0x7f86b5afad70> Traceback (most recent call last): File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/utils/autoreload.py", line 250, in raise_las t_exception six.reraise(*_exception) File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/opt/rh/python27/root/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 52, in <mod ule> class AbstractBaseUser(models.Model): File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/db/models/base.py", line 124, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/db/models/base.py", line 330, in add_to_clas s value.contribute_to_class(cls, name) File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/db/models/options.py", line 214, in contribu te_to_class -
django RequestFactory loses url kwargs
I am trying to switch from using Django Test Client to RequestFactory to speed up my tests. However, requests generated by RequestFactory do not supply proper kwargs to views. Example: this is my view class SomeView(View): def get(self, request, *args, **kwargs): return JsonResponse({'your kwargs': str(kwargs)}) with urlconf url(r'^some_view/(?P<some_kwarg>[\-0-9a-fA-F]+)/$', views.SomeView.as_view(), name='some_view'), and two tests: def test_different_kwargs(): c = Client() response = c.get( reverse('bots:some_view', kwargs={'some_kwarg': '12345'}), ) print('\n\nResponse for TestClient: ', response.content.decode()) rf = RequestFactory() request = rf.get( reverse('bots:some_view', kwargs={'some_kwarg': '12345'}), ) response = SomeView.as_view()(request) print('\n\nResponse for RequestFactory: ', response.content.decode()) What they produce is: Response for TestClient: {"your kwargs": "{'some_kwarg': '12345'}"} Response for RequestFactory: {"your kwargs": "{}"} So, what's the point of RequestFactory if it loses url kwargs? Or is there a way to put them into the view somehow? -
Is there a way that a Django template include is not silent if it fails for developement
I would like to have the possibility that include templates are not silent when they fail Let me explain.. We have a main template A. We have a template to include B that contains an error. When we include template B, this one will not be displayed because it contains an error even if the template_debug = True, and it looks fine. The fact that fails are silent is convenient for a production environment. However, often on the environment of development this can pose problem insofar we do not see that there is a problem since it does not appear. Even if we can often see the error in the console. Also for the debug it is relatively painful as sometimes we do not know where the error comes from. So my question is: would there be a solution (ex: custom template tag include_noisy, or middleware) for the template include not silentious on local machines, and thus correctly display errors as in a normal template? For sure, the silent is still always present when the template_debug = False Thanks in advance -
Django - displaying images on the page using pyuploadcare
Python, Django, pyuploadcare, html5, jquery, The Django documentations for pyuploadcare are useful for image customization and file uploading and stuff like that, but what they don't tell you is how to display the image in the webpage. For example, i can display the URL where the image is stored, but i cannot display the image itself in the webpage i want to make this as clear as possible to the reader so I'll give another example: To build an image gallery, i would need all the images displayed on one page, i can do that using the for loops for photo in photos Photo and photos are defined in views.py {% extends 'base.html' %} {% for photo in photos %} {{ photo.caption }} {{ photo.photo }} {% endfor %} {% block content %} {% endblock %} photo.caption is an models.CharField() photo.photo is an ImageField() from from pyuploadcare.dj.models import ImageField everything is working properly but i don't know how to display the images on the webpage. Any help would be apreciated -
Django get_model not return parent inheritance
I have the next models: class Parent(models.Model): name = models.CharField() class Child(Parent): number = models.IntegerField() If I do apps.get_model('myapp', 'Child') and for c in Child.objects.all() it will give me the error Cannot resolve keyword 'name' into field. I don't actually need the name field in my migration. How should I use Child without importing it from the model file? -
wagtail 2.0b1 admin static files issue
Updating my wagtail to 2.0b1, I am getting a warning about wagtailadmin static files and no styling is applying to my admin page. ( also when collectstatic command runs no wagtile files are copying ) WARNINGS: ?: (wagtailadmin.W001) CSS for the Wagtail admin is missing HINT: Most likely you are running a development (non-packaged) copy of Wagtail and have not built the static assets - see http://docs.wagtail.io/en/latest/contributing/developing.html File not found: /Users/burakk/BurakWorks/Web/VIRTUAL_ENVIRONMENTS/python3.6.1/src/wagtail/wagtail/admin/static/wagtailadmin/css/normalize.css I have checked the wagtail 2.0b1 folder and there is a 'static_src' folder instead of a folder named 'static'. I have checked the previous stable version's admin folder and there is also a 'static_src' folder so that is not the problem I think? -
django api call from view change time data from get
I have a view where when it call an api, it will save the result get from it. But i want to be able to change the time get from Post method to like +30min or +1hr and save it. In my case, there is a starttime and endtime. But there is only a field time given back. So i will save the time into starttime and time+30min/1hr save into endtime How do i do it ? views @csrf_exempt def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/makeapp/', data=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/makeapp/', data=request.GET) if r.status_code == 201 and request.method == 'POST': data = r.json() print(data) # Create a schedule/Save to schedule table user = data['patientId'] userId = MyUser.objects.get(userId=user) # time gettime = data['time'] gettime_add = ??? saveget_attrs2 = { "userId ": userId , "starttime": data["time"], "date": data["date"], } saving2 = Schedule.objects.create(**saveget_attrs2)