Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
View UrlGatewayLogin didn't return an HttpResponse object. It returned None instead
It's a bit repetitive but this error is everywhere to find, but I'm a bit confused about what is happening, so I'm trying to pass a token in the url for the user to login like so http://localhost:8000/auth/login/?token=token and after the user is authenticated it should be redirected to dashboard. But I'm getting this ERROR, can you help me understand what is happening. View: import logging from django.contrib.auth import authenticate, login from django.core.urlresolvers import reverse, reverse_lazy from django.shortcuts import render from django.views.generic import View from django.http import HttpResponseRedirect, Http404, HttpResponse from django.contrib.auth.backends import ModelBackend from rest_framework_jwt.settings import api_settings from business_accounts.models.my_user import MyUser logger = logging.getLogger(__name__) jwt_decode_handler = api_settings.JWT_DECODE_HANDLER class UrlGatewayLogin(View): def get(self, request, **kwargs): page_group = kwargs.get('page_group') token = request.GET.get('token') try: payload = jwt_decode_handler(token) user = MyUser.objects.get(pk=payload.get('id')) user.backend = 'django.contrib.auth.backends.ModelBackend' except MyUser.DoesNotExist: return None authenticate(token=token) logger.warning("User is=%s", user) print(user) login(request, user) return HttpResponseRedirect('dashboard', {'page_group': page_group}) url: url(r'^auth/login/$', UrlGatewayLogin.as_view(), name='auth-login') -
How to divide a large Django project into sub projects for scaling?
In this Django large-scale (e-commerce website) project that we need to divide into sub-projects as a Buyer, Seller, and Admin and will create three databases also accordingly. So how can I manage the same Models in 3 projects?. -
Django DateTimeField with widget from DateTimePickerInput (django-bootstrap-datetimepicker-plus)
I'm currently trying to use django-bootstrap-datetimepicker-plus in one of my forms. It works absolutely fine when testing on localhost, but does not display calendar when deployed on pythonanywhere.com. I tried using other widgets with similar functionality but it didn't change anything. Whole app: https://github.com/MarekCiborowski/De_Dzango -
DJANGO: djangorestframework-jwt: How to access the user and jwt_value returned in my view if the jwt token is valid one
I am trying to understand the middleware of djangorestframework-jwt i.e: "rest_framework_jwt.authentication.JSONWebTokenAuthentication" BaseJSONWebTokenAuthentication class has a function called authenticate as shown below which will return a tuple. How to access the tuple in my view. def authenticate(self, request): """ Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`. """ jwt_value = self.get_jwt_value(request) if jwt_value is None: return None try: payload = jwt_decode_handler(jwt_value) except jwt.ExpiredSignature: msg = _('Signature has expired.') raise exceptions.AuthenticationFailed(msg) except jwt.DecodeError: msg = _('Error decoding signature.') raise exceptions.AuthenticationFailed(msg) except jwt.InvalidTokenError: raise exceptions.AuthenticationFailed() user = self.authenticate_credentials(payload) return (user, jwt_value) -
How to highlight some words in a non-readonly field in django admin?
I have a "models.TextField" which is editable in Admin. How can I highlight certain words in it such that when someone opens admin for this model those words are highlighted. In addition, when you change the field value, I want those highlights (probably markdowns in the text) not to be considered when saving the model. -
Django Channels: Connect to Sockets
I'm setting up Django Channels and so far this is the code I've put up. #routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import routing as route from django.conf.urls import url from consumers import ChatConsumer websocket_urlpatterns = [ url(r'^ws/chat/$', ChatConsumer), ] application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), }) and in consumers.py from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) and settings file #Channels ASGI_APPLICATION = 'chatsys.routing.application' and finally the javascript //Sockets var myWebSocket = new WebSocket("ws://" + window.location.host + "/chat/"); myWebSocket.onopen = function(evt) { alert("Connection open ..."); }; myWebSocket.onmessage = function(evt) { alert( "Received Message: " + evt.data); }; myWebSocket.onclose = function(evt) { alert("Connection closed."); }; // Call onopen directly if socket is already open if (myWebSocket.readyState == WebSocket.OPEN) myWebSocket.onopen(); //End Sockets What I get when the page loads is the alert for onclose alert("Connection closed."); and also on the console a 404 for the ws connect to ws://35.227.80.72/chat/ -
POST request Parameters from Class based views - Pagination
I'm using Django's Pagination Module with class-based views. My Queryset will contain 1000+ objects, which I need to display one by one and based on the content displayed. I don't need to show previous pages, I just need to Accept/Reject and on both the clicks, it should paginate to the next page. I need to update few fields in the database based on Accept/Reject clicked by the user. How can I get the POST request parameters from the template in my class-based view? so that I can perform different steps on the click of Accept/Reject Here's my code: #views.py from django.views.generic import ListView class DemoView2(ListView): model = MandateTable template_name = 'demo2.html' context_object_name = 'pg' paginate_by = 1 queryset = MandateTable.objects.all()[:5] #For Testing purspose, working on only 5 objects Template <!--demo2.html--> {% for mandates in pg %} <p>{{ mandates.FIELD_1 }}</p> <p>{{ mandates.FIELD_2 }}</p> <p>{{ mandates.FELD_3 }}</p> <p>{{ mandates.FIELD_4 }}</p> <p>{{ mandates.FIELD_5 }}</p> {% endfor %} {% if is_paginated %} <ul class="pagination"> {% if page_obj.has_previous %} <li><a href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} <button value="Accept" name="btn-accept" class="btn btn-success btn-lg"> {% if page_obj.has_next %} <a style="text-decoration: none" href="?page={{ page_obj.next_page_number }}">Accept</a> {% else %} <a style="text-decoration: none" href="{% url … -
In django, I'm not able to receive my form data via POST
It's Saleor ecommerce Framework, i want to know the possibilities of occurring this type of issue. My HTML: <form method="post" action="{% url 'product:add-to-cart' product_id=product.pk slug=product.get_slug %}" novalidate> <input type="text" name="test" value="testval"> {% bootstrap_field form.quantity %} {{ form.check_out }} {{ form.check_in }} </form> My URL: urlpatterns = [ url(r'^(?P<slug>[a-z0-9-_]+?)-(?P<product_id>[0-9]+)/$', views.product_details, name='details'), url(r'(?P<slug>[a-z0-9-_]+?)-(?P<product_id>[0-9]+)/add/$', views.product_add_to_cart, name="add-to-cart") ] My Form: class AddToCartForm(forms.Form): quantity = QuantityField( label=pgettext_lazy('Add to cart form field label', 'Quantity')) check_out = forms.ModelChoiceField( queryset=ProductType.objects.all(), label=pgettext_lazy('Product type form label', 'Product type'), widget=forms.RadioSelect, empty_label=None) check_in = forms.HiddenInput() } My View: def product_add_to_cart(request, slug, product_id): # types: (int, str, dict) -> None my_request = request [MY DEBUG BOOKMARK HERE..] In my HTML form i can submit for "quantity", but other three fields i can't receive. my debug response is : <QueryDict: {'quantity': ['1']'}> Why i'm not getting remaining fields ? -
ImportError: Unable to find zbar shared library
I am trying to make a online bar code reader using Django framework and deploying it on Heroku. But when I load the the page it is showing this error: ImportError at / Unable to find zbar shared library Request Method: GET Request URL: https://libportal.herokuapp.com/ Django Version: 2.0.3 Exception Type: ImportError Exception Value: Unable to find zbar shared library Exception Location: /app/.heroku/python/lib/python3.6/site-packages /pyzbar/zbar_library.py in load, line 65 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.4 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Thu, 31 May 2018 11:02:16 +0000 I searched on it and found one appropriate solution here. But in my case pyzbar is successfully installed using pip and then after I installed libzbar-dev by adding it into Aptfile file after seeing above solution. Can anyone please help me in this? -
Form field rendering as hidden in Django Forms
I have a below form content = forms.CharField(widget=CKEditorWidget()) helper = FormHelper() helper.form_method = 'POST' helper.form_class = 'form-horizontal' helper.layout = Layout( Field('name', css_class='form-control'), Field('meta_title', css_class='form-control'), Field('meta_keyword', css_class='form-control'), Field('meta_description', css_class='form-control'), Field('content',css_class="form-control"), Field('status'), FormActions(Submit('submit', 'submit', css_class='btn-primary'))) class Meta: model = SongdewPages fields = ['name','meta_title','meta_keyword','meta_description','content','status'] enter code here The form is rendering the content field as hidden. Here is my html page {% extends 'core/base.html' %} {% load crispy_forms_tags %} {% block content %} {% crispy form %} {% endblock %} If I remove the {% extends 'core/base.html' %}, {% block content %}, {% endblock %}, content field (which is a CKeditor) displays properly, otherwise it is shown as hidden while doing inspect element. I am new to Django forms and can not seem to find its solution. -
Why does el-pagination load at once?
I followed the docs but I can't figure out why it updates the pagination as soon as I scroll. What I want to achieve is that it loads new content when it hits the bottom of the page but for some reason it loads the whole content at once as soon as I scroll. Has someone experienced the same thing ? How can I fix this? :/ -
Unable to delete files in an Django API call in Azure webapp
I am trying to programatically delete a directory that I created in an API call to Django Server. But I am getting errors. So far, I have tried 2 approches - def del_tree(dirpath): os.chmod(dirpath, stat.S_IWUSR) os.remove(dirpath) When this function is called it throws error at os.remove line saying Access is denied. Other approch was to use just shutil.rmtree. This one gave an error saying File is being used by another process. Any idea how to fix this? -
I need help in django.db.utils.IntegrityError: UNIQUE constraint failed
Im unable to debug this django.db.utils.IntegrityError: UNIQUE constraint failed: post_employee.employee_id, when i'm saving value through my inbuilt admin then its working fine but when i am editing those values then its raising integrityError. Please have a look at my code and correct me. Please models.py from django.db import models from django.db.models.signals import post_save # Create your models here. class Person(models.Model): name = models.CharField(max_length=100) gender = models.CharField(max_length=10) def __str__(self): return (self.name) class Employee(models.Model): employee = models.OneToOneField(Person,on_delete=models.CASCADE) emp_no = models.CharField(max_length=100) desgnation = models.CharField(max_length=100) def __str__(self): return str(self.employee) def create_profile(sender,**kwargs): if kwargs: Employee.objects.create(employee = kwargs['instance']) post_save.connect(create_profile,sender=Person) Errors IntegrityError at /admin/post/person/1/change/ UNIQUE constraint failed: post_employee.employee_id Request Method: POST Request URL: http://localhost:8000/admin/post/person/1/change/ Django Version: 2.0.5 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: post_employee.employee_id In database i am seeing employee_id - integer - employee_id NOT NULL UNIQUE Is this IntegerityError coming for this UNIQUE,Then how to correct it? -
How to pre select django forms.CheckboxSelectMultiple
I am having a MultipleChoiceField to select language choices from a list of 7 languages. LANGUAGES = ( ('en', _('English')), ('pl', _('Polish')), ('da', _('Danish')), ) Inside my forms.py, I have language = forms.MultipleChoiceField(choices=LANGUAGES, widget=forms.CheckboxSelectMultiple) I am trying to pre select choices when the page is loaded. I have tried self.fields['language'].widget.attrs.update({'initial': selected_languages}) and self.fields['language'].initial = selected_languages my selected_languages has value like ['en', 'fr' ] I this the right way to pre select fields in django forms? This method is not working for me. Is there any other method? NB: I am using this form inside django admin -
Django tag detail page with taggit
I've a very similar problem like this post. Long story short, I've got a django blog, and for tags I'm using django-taggit which is working nice on the admin page. AdminScreen My main problem is that if I like to filter to a tag by an url address I still receive a 404 error although I red the documentation and couple of stackoverflow post: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8080/tag/sample/ views.py from django.utils import timezone from .models import Post from django.shortcuts import render, get_object_or_404 from taggit.models import Tag def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) def tag_detail(request, tag): tag = get_object_or_404(Tag, tag=tag) return render(request, 'blog/tag_detail.html', {'tag': tag}) urls.py(app) from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'), url(r'^tag/(?P<tag>[-/w]+)/$', views.tag_detail, name='tag_detail'), ] models.py from django.db import models from django.utils import timezone from taggit.managers import TaggableManager class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) tags = TaggableManager() def ttags(self): return [t.name for t in self.tags.all()] def publish(self): self.published_date = timezone.now() self.save() def … -
Django/gettext with unused arguments
I have the following piece of code in a Django template: {% blocktrans %} {{ c_type }} from {{ organization }}, buddy. {% endblocktrans %} The Swedish translation of this is set to: Info från {{ organization }}, kompis. Note that the translation doesn't ever use c_type, it's irrelevant entirely in Swedish. When I run compilemessages, I get the following: CommandError: Execution of msgfmt failed: /app/locale/sv/LC_MESSAGES/django.po:1381: a format specification for argument 'c_type' doesn't exist in 'msgstr' msgfmt: found 1 fatal error Is there a way to silence this error? -
django celery SQS "No result backend is configured."
Not duplicate of Celery: No Result Backend Configured? since using SQS Keep getting the following error: No result backend is configured. Please see the documentation for more information. My production settings are the following: CELERY_BROKER_URL = 'sqs://%s:%s@' % ( urllib.parse.quote(env.str('TASK_QUEUE_USER_ID'), safe=''), urllib.parse.quote(env.str('TASK_QUEUE_USER_SECRET'), safe='')) BROKER_URL = CELERY_BROKER_URL CELERY_ENABLE_REMOTE_CONTROL = False CELERY_RESULT_BACKEND = None # Disabling the results backend RESULT_BACKEND = None # Disabling the results backend CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_DEFAULT_QUEUE = 'async_tasks' SQS_QUEUE_NAME = 'async_tasks' CELERY_ENABLE_REMOTE_CONTROL = False CELERY_SEND_EVENTS = False CELERY_BROKER_TRANSPORT_OPTIONS = { 'region': 'eu-west-2', 'polling_interval': 3, 'visibility_timeout': 3600, } CELERY_SEND_TASK_ERROR_EMAILS = True # # https://stackoverflow.com/questions/8048556/celery-with-amazon-sqs#8567665 # CELERY_BROKER_TRANSPORT = 'sqs' BROKER_TRANSPORT = 'sqs' Running celery from the command line: DJANGO_ENV=production celery -A async_tasks worker -l info connects to SQS and polls, but when I try to do a demo call from the command line DJANGO_ENV=production python manage.py check_async: from django.core.management.base import BaseCommand, CommandError import async_tasks.tasks as tasks class Command(BaseCommand): help = 'Check if infrastructure for async tasks has been setup correctly.' def handle(self, *args, **options): try: print('Sending async request.') t = tasks.add.apply_async((2, 4)) out = t.get(timeout=1) print(out) print(t.status) except Exception as e: print(e) raise CommandError('Error occured') I get the error above. Have tried in … -
How to use Django FileField with dynamic Amazon S3 bucket?
I have a Django model with a Filefield, and a default storage using Amazon S3 bucket (via the excellent django-storage). My problem is not to upload files to a dynamic folder path (as we see in many other answers). My problem is deeper and twofold: Files are already inside an Amazon S3 bucket, and I do not want to download-reupload them (worse: I have only a read-access to them). Files are accessible through S3 credentials that could be different from one file to another (that is, files can be located inside different buckets, and access through different credentials). Hence, my FileField must have a dynamic storage. Any idea? (Djabgo 1.11, Python 3). -
Add a value to Django's date input settings
I need to add a specific date format to the DATE_INPUT_FORMATS setting. Now, there is already a default value (a list of formats) for DATE_INPUT_FORMATS - and I want to append my format to that list. What is the best way to go about this? Of course, I'm trying to avoid overriding the default definition. -
how mock allows checking the arguments sent to the mocked function in django testing
This is the method where i want to mock send_email() def send_set_password_email(self): self.update_hash() url = self.user.password_set_url() recipient = self.user.email context_dict_map = {} context_dict_map[recipient] = Context(dict( partner_realtor_obj=self, full_name=self.contact_name, change_password_url=url, slug=self.slug, host = "http://%s.moveeasy.com/" % (self.slug, ), STATIC_URL = settings.EMAIL_STATIC_URL )) if self.brokerage_link: subject = '%s has empowered you with MoveEasy' % (self.brokerage_link.name) else: subject = 'You have been empowered with MoveEasy' send_mail( recipients=[recipient], subject=subject, text_content='Set your password at the following url: %s' % (url,), template_name='emails_table/realtors/set-password.html', context_dict_map=context_dict_map, subdomain=self.slug, email_type='Realtor: Set password' ) In my testcase i have mocked it like @mock.patch('moving_concierge.utils.send_mail') def test_send_set_password_email(self, send_mail): image_content = open( os.path.join(settings.BASE_DIR, 'static/images/avatar.jpg'), "rb" ).read() logo = SimpleUploadedFile('image.jpg', image_content) user = User.objects.create_realtor( email='john@doe.com', password='Abc123!' ) realtor = RealtorDetails.objects.create( user=user, slug='john-doe', logo=logo, hash='j12h9on8' ) realtor.send_set_password_email() url = realtor.user.password_set_url() send_mail.returnvalue = context_dict_map I need to Assert that proper context_dict_map is passed to send_mail, How can i do that ??? Please help me out guys, Thanks in advance. -
Pass data between UpdateView and CreateView in Django
I had two models Permit & Course. class Permit(models.Model): name = models.CharField(max_length=50) skill_course = models.ManyToManyField(Skill, related_name="+", blank=True) class Course(models.Model): name = models.CharField(max_length=50) skills = models.ManyToManyField(Skill, related_name="courses",blank=True,) students = models.ManyToManyField(User, related_name="courses",blank=True,) Clicking a permit object displays students who acquired permit dynamically(in UpdateView with GET method). How to create course with those students?(in CreateView with POST method) Do I have to pass data between 2 views? I want to create a utils.py file, there create a method with data I will reuse in other methods or class, but the class or function will have request and pk, I don't know how to return a dict, because it should be have request and template right? I was trapped in this, really appreciate for any help, thanks in advance...... -
Django Paho MQTT Client Connection and Running Problems
I'm developing a Django app which uses Paho MQTT. I have problems about where I should place MQTT code in order to run it on startup. By now, I tried putting MQTT related code to mqtt.py import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) client.subscribe("test") def on_message(client, userdata, msg): print(msg.topic + " " + str(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("iot.eclipse.org", 1883, 60) and to run this code on startup, I changed my_app/apps.py and my_app/__init__.py # apps.py from django.apps import AppConfig class IotCloudAppConfig(AppConfig): name = 'iot_cloud_app' def ready(self): from .mqtt import client client.loop_start() # __init__.py default_app_config = 'IotCloudAppConfig' There are two problems right now. 1) On startup, on_connect is called twice and this causes some problems. (i.e. the code inside on_connect is run twice so topics are subscribed twice) I tried to debug this (on PyCharm) but eventhough on console I can see that print statement is printed twice, breakpoint is only reached once. 2) I have a model called Device that stores an MQTT topic in its fields and when on_connect method in mqtt.py is called, I want to iterate over all Device records in database and … -
dajngo rest api paypal integration
i am new in payment integration.i am tryoing to do paypal integration with django rest api.i have a function in view like this. from django.http import HttpResponse,JsonResponse import paypalrestsdk import logging def paypal(requet): print("dfdfdf") paypalrestsdk.configure({ "mode": "sandbox", # sandbox or live "client_id": "AY2_iKWa8vJNi7FLrXf5Buf3HDQ4HHTjO_wv5O9-OMyO8IkTzud8iKKaNPp7cfXCacy4r6SlxD_RgXYu", "client_secret": "EJoUuQXt1pVTMzMc-fuvmiVIUbrqW2yJRW3CH30iMsxA-e87SMddlrEEiY9D_G5RfbvwwUaRK9lWPJwE" }) payment = paypalrestsdk.Payment({ "intent": "sale", "payer": { "payment_method": "paypal"}, "redirect_urls": { "return_url": "http://localhost:3000/payment/execute", "cancel_url": "http://localhost:3000/"}, "transactions": [{ "item_list": { "items": [{ "name": "item", "sku": "item", "price": "5.00", "currency": "USD", "quantity": 1}]}, "amount": { "total": "5.00", "currency": "USD"}, "description": "This is the payment transaction description."}]}) print(payment) if payment.create(): print("Payment created successfully") else: print(payment.error) return HttpResponse("success") i got this success response both in postamn and create a history in sandbox api calling history.but no data found in facilitator account.what is the reason and what will be the solution?kindly help me. -
Model.clean method is called after ModelForm.clean method raised ValidationError
As an example, I have next model and form. class TestModel(models.Model): first = models.FloatField() second = models.FloatField() def clean(self): # I expect that this code will not run # because TestForm raises ValidationError self.first *= 2 self.second *= 4 class TestForm(forms.ModelForm): def clean(self): cleaned_data = super().clean() if cleaned_data['first'] > cleaned_data['second']: raise forms.ValidationError('Not allowed') class TestAdmin(admin.ModelAdmin): form = TestForm fields = ('first', 'seconds') I suppose that TestModel.clean method is not going to execute, because TestForm.clean method raised forms.ValidationError, but TestModel.clean executes. Why? -
Deploy Django static files with Apache/Gunicorn
I am using Apache2 with Gunicorn/Django to deploy my app. However my app doesn't display the static files like CSS sheets etc. I read many topics but I think I need help because I probably missed something... Setting.py ALLOWED_HOSTS = ['localhost'] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join('static'), ) STATIC_ROOT = '/var/www/media/myapp/static/' Apache2 VHost <VirtualHost *:80> ServerName myapp.fr ServerAlias www.myapp.fr myapp.fr DocumentRoot /home/django-project/myapp/ <Proxy *> Order deny,allow Allow from all </Proxy> ProxyPass / http://localhost:9000/ ProxyPass /static/ ! Alias /static/ /var/www/media/myapp/static/ <Directory /home/django-project/myapp/> Order deny,allow Allow from all Options -Indexes </Directory> </VirtualHost>