Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send own string in response using WebSockets
I am trying to create real-time chat between Django backend and Angular 4 frontend using PostgreSQL database. Let's assume that I would like to create chatbot for instance like A.L.I.C.E. I am not sure but it seems to me that the most optimal solution would be to use websockets? I would like to write message on frontend, press enter and send my message to backend. Then I would like to get a response. I am trying to do this in the way shown below, however I would like to send in response my own string, not the one that is sent from frontend. By the way, is it done properly? routing.py: from channels.routing import route from backend.consumers import ws_connect, ws_receive, ws_disconnect channel_routing = [ route("websocket.connect", ws_connect), route("websocket.receive", ws_receive), route("websocket.disconnect", ws_disconnect), ] consumers.py: # In consumers.py from channels import Group # Connected to websocket.connect def ws_connect(message): # Accept the connection message.reply_channel.send({"accept": True}) # Add to the chat group Group("chat").add(message.reply_channel) # Connected to websocket.receive def ws_receive(message): Group("chat").send({ "text": message.content['text'], }) print(message.content['text']) # Connected to websocket.disconnect def ws_disconnect(message): Group("chat").discard(message.reply_channel) -
Heroku looking for Procfile in wrong directory
I'm trying to work with Django on Heroku and I'm following this tutorial with its Django template https://devcenter.heroku.com/articles/django-app-configuration https://devcenter.heroku.com/articles/deploying-python But when i run 'heroku local web' it always look in the wrong directory. I've tried to move the project (env) D:\Study\Workbench\heroku-testing\testing\env\codeShareApp>heroku local web [WARN] No ENV file found [WARN] ENOENT: no such file or directory, open 'C:\Users\William\Procfile' [FAIL] No Procfile and no package.json file found in Current Directory - See run_foreman.js --help The project directory is as follows env/ codeShareApp/ .idea/ codeShareApp/ .env manage.py Procfile requirements.txt runtime include/ Lib/ Scripts/ tcl/ -
Install Django in Ubuntu 16.04
How do i Install Django in Ubuntu 16.04? I have not yet installed but i would like some advice on installation. I have tried pip install django but it brings errors -
Python Import Error: No module named webpack_loader
I've tried to look at similar questions but have really struggled to find a solution to this problem. I know that there's going to be some super smart software engineer that has a better idea than I do though! I have a single page website I've built in react.js with django backend. It works on my computer but won't work when I have tried to load it into a server (PythonAnywhere). Really fustrated as I was really looking forward to having it online. The error I'm receiving is below : Unhandled exception in thread started by <function wrapper at 0x7f67f8b4cb90> Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named webpack_loader I have had a look at making clear the encoding for the init.py code, I think it may relate to my settings.py static_root and webpack_loader settings which are … -
Django: couple of objects with unique methods, accessable by ForeignKey
Imagine, we have couple (let's say, ten) object. Every object represnt web site (for example), and have method get_value for scrap some data from this site. This method is unique for every object. Fields of objects are same. These objects is static and not require edit in runtime. Then, in models we need ForeignKey to this objects: class Data(models.Model): data_source = models.ForeignKey(?????) What a best and pythonic way to represent this data structure? -
django rest framework serialize the related fields
models.py class Category(models.Model): name = models.CharField(max_length=128) class Product(models.Model): category = models.ManyToManyField(Category, related_name="category") name = models.CharField(max_length=128) class ProductVariation(models.Model): product = models.ForeignKey(Product, related_name="product") name = models.CharField(max_length=128) serializers.py class ProductVariantSerializer(serializers.HyperlinkedModelSerializer) class Meta: model = ProductVariation fields = ( "name", ) class CategoryDetailSerializer(serializers.Modelserializer): product_variant = PromotionVariantSerializer(many=True) class Meta: model = Category fields =( "name", "product_variant" #how can i do this ) here i want to list all the product variant that belongs to the category. can i do this way or i want to write methods to get the product variant details -
Django 1.11 - How to use height_field and width_field with ImageField
I've the defined the following model which it's used in my Django application for storing the images with different dimensions. class Image(models.Model): def _img_path(instance, filename): # file will be uploaded to MEDIA_ROOT/<instance.path>/<filename> return '{0}/{1}'.format(instance.path, filename) id = models.AutoField(primary_key=True) path = models.CharField(max_length=500) img = models.ImageField(upload_to=_img_path, max_length=500, height_field='img_height', width_field='img_width') img_md = models.ImageField(upload_to=_img_path, max_length=500, height_field='img_height', width_field='img_width', null=True) img_sm = models.ImageField(upload_to=_img_path, max_length=500, height_field='img_height', width_field='img_width', null=True) img_xs = models.ImageField(upload_to=_img_path, max_length=500, height_field='img_height', width_field='img_width', null=True) Since I'm using the Django REST Framework for APIs, the following is the code of the serialiser that saves images: class ProductDrawingSerializer(ModelSerializer): drawing = ImageSerializer() class Meta: model = ProductDrawing fields = [ 'product', 'drawing', ] def create(self, validated_data): product = validated_data['product'] filename = 'product-{0}.{1}'.format(product.pk, 'jpg') filename_xs = 'product-{0}_{1}.{2}'.format(product.pk, 'xs', 'jpg') # resize_image() is just function I wrote that uses the Pillow Image.resize() resize_image(validated_data['drawing']['img'], 'temp_files/'+filename, max_w=1500.0, max_h=1500.0, max_file_size=0.7, to_jpeg=True) resize_image(validated_data['drawing']['img'], 'temp_files/'+filename_xs, max_w=120.0, max_h=120.0, max_file_size=0.01, max_img_quality=98, to_jpeg=True, do_trim=True) drawing = Image() drawing.path = 'drawings' drawing.img.save(filename, File(open('temp_files/'+filename, 'rb')), save=False) drawing.img_xs.save(filename_xs, File(open('temp_files/'+filename_xs, 'rb')), save=False) drawing.save() product_drawing = ProductDrawing(product=product,drawing=drawing) product_drawing.save() return product_drawing I don't know why, but I'm getting an AttributeError: 'Image' object has no attribute 'img_width' I thought the attributes height_field and width_field were auto-popolutated. How to proper use them? -
Is a position of adding @csrf_exempt wrong?
I wanna connect my Swift app & Python Django Server in sending Image(I wanna send images from Swift app to Server) When I tried to do it,I got an error in Xcode <div id="info"> <h2>Help</h2> <p>Reason given for failure:</p> <pre> CSRF cookie not set. </pre> <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when <a href="https://docs.djangoproject.com/en/1.10/ref/csrf/">Django's CSRF mechanism</a> has not been used correctly. For POST forms, you need to ensure:</p> <ul> <li>Your browser is accepting cookies.</li> <li>The view function passes a <code>request</code> to the template's <a href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a> method.</li> <li>In the template, there is a <code>{% csrf_token %}</code> template tag inside each POST form that targets an internal URL.</li> <li>If you are not using <code>CsrfViewMiddleware</code>, then you must use <code>csrf_protect</code> on any views that use the <code>csrf_token</code> template tag, as well as those that accept the POST data.</li> <li>The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.</li> </ul> <p>You're seeing the help section of this page because you have <code>DEBUG = True</code> in … -
Filter by object field in django-graphene
I am writing a web application using django-graphene. I try to filter by my models fields. Models: class Tire(models.Model): width = models.IntegerField() class Spec(models.Model): manufacturer = models.TextField() tire = models.ForeignKey(Tire) Types: class TireType(DjangoObjectType): class Meta: model = data.models.Tire filter_fields = { 'width': integer_filters } class SpecType(DjangoObjectType): class Meta: model = data.models.Spec filter_fields = { 'manufacturer': string_filters 'tire__width': integer_filters } From this models and types I can filter by the fields (using the arithmetic operations gt, lt etc...). I want to filter by an object (graphene field maybe?), so instead of: { allTires(width_gt: 5 width_lt: 10) { ... } } I want to execute this: { allTires(input: { width_gt: 5 width_lt: 10 }) { ... } } Finally I want to achieve nested filters for foreign keys, for example: { allSpecs(manufacturer: "toyota" tireFilter: { width_gt: 5 width_lt: 10 })} { ... } } How can I do this? -
Isomorphic fetch and Django view
I'm sending a POST request to Django view using isomorphic fetch. body : "{"email":"admin@example.com","password":"11"}" credentials : "same-origin" headers : Accept : "application/json" Content-Type : "application/json" X-CSRFToken : "mudIfipiyLUao2ZWwoEotFOUknYeVpZASNpQQ2IdadRVOe0a9n5tUqcKzwtrDuWX" method : "POST" When I send this request to DRF view, I can read the data using request.data. However when I send the same data to Django view, request.POST is empty. What could be the reason? -
Django crispy form horizontal layout
I'm trying to create a contact form page using crispy forms and bootstrap with a template that shows the labels on the left side and the input fields on the right side on large viewport size but it's looking weird. What am I doing wrong? See image below. forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Div, Field, Button from crispy_forms.bootstrap import StrictButton, FormActions class ContactForm(forms.Form): from_email = forms.EmailField(required=True) CHOICES = ( ('1','General Questions/Comments'), ('2','Correction'), ('3','API Access Request'), ) subject = forms.ChoiceField(widget=forms.Select, choices=CHOICES) website = forms.CharField(widget=forms.TextInput(attrs={'maxlength': '50',}), required=False) message = forms.CharField(widget=forms.Textarea, required=True) def __init__(self, *args, **kwargs): #self.user = kwargs['initial']['user'] super(ContactForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-8' self.helper.layout = Layout( 'from_email', 'subject', 'website', 'message', StrictButton('Send', css_class='btn-default'), ) email.html template {% extends 'base.html' %} {% load crispy_forms_tags %} {% block headcontent %} {% endblock %} {% block content %} <div class="container"> <div class="row row-centered"> <div class="col-md-8 col-centered"> <div class="well well-lg"> <h1>Contact Us</h1> <form method="post"> {% csrf_token %} {% crispy form form.helper %} </form> </div> </div> </div> </div> {% endblock content %} This is what it looks like -
Logging in user through Django rest framework
I'm trying to log in a user through DRF view. @list_route(methods=['post']) def login(self, request, *args, **kwargs): login_form = LoginForm(request, data=request.data or None) if login_form.is_valid(): _login(request._request, login_form.get_user()) else: raise forms.ValidationError("login wrong") return Response({}) Above code runs without exception, but it doesn't seem to actually log in the user. When I refresh the browser, the user is still not logged in. How can I log in the user? -
How to correctly import models in extra modules in Django project?
If i want to use some model in extra file in my Django project, i can't do it by this simple way: from myproject_app.models import * because i get this error: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. To solve this problem, I found this solution: import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") django.setup() from myproject_app.models import * Ok. It works. But if i want to use any fuction from this extra file in models.py project does not start at all! Please help me. -
Django Server IP Address
I'll list the details here: Server is on a VM. Host Machine is connected to WiFi @ 10.44.8.54 VM Network Adapter (NAT) @ 192.168.13.1, VM IP shows 192.168.13.133 I can access server on guest and host machine @ 192.168.13.133:8000 (ran server on 0.0.0.0:8000) I have another device connected to the WiFi at 10.44.8.46 How can I access the server from that device? Thank you -
Django Swagger not showing urls without permission Class
I am setting up Django-rest-swagger for my project. I have following settings for Django-restframework. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } Now, when I have View with some permission class like this class CreateUserView(viewsets.ModelViewSet): serializer_class = UserServiceSerializer authentication_classes = [] permission_classes = [] class UserProfileView(viewsets.ModelViewSet): serializer_class = UserProfileSerializer serializer_class_2 = UserServiceSerializer I see following view But when add permission_classes in both view like this class CreateUserView(viewsets.ModelViewSet): serializer_class = UserServiceSerializer authentication_classes = [] permission_classes = [] class UserProfileView(viewsets.ModelViewSet): serializer_class = UserProfileSerializer serializer_class_2 = UserServiceSerializer permission_classes = [] I see view like this I do not want to add permission class in every view as I have same class for all my view and I have mentioned that in my rest-framework setting. How can I do that? -
How to manipulate the position of an input box?
I am trying to put the drop down boxes and the input box on the same line. However, the input box keeps floating to the bottom. enter image description here <div style="margin-left: 2%; font-size:10";> <h1 style="font-size:15px;color:#343538">Geographical Constraint</h1> <div class=".col1"> <select class="selectpicker" > <option>USA</option> <option>CA</option> </select> <select class="selectpicker"> <option>=</option> <option>></option> <option><</option> <option>>=</option> <option><=</option> </select> </div> <div class="col-xs-2"> <input type="value" class="form-control" id="val"> </div> </div> -
Django-real time notifications
I am working on a portal for an university.One of my use-case is real-time notifications.For ex: If a faculty or a TA uploads an assignment/grades it/uploads an answer -- all the students should be notified. What is the best way to do it,without any third party tools?.Also,a weekly consolidated email should be sent to students,faculty, TAs..I have looked into other solutions, but could not yet come to a conclusion on which will work. -
Adding a new field along with username and password in django's login form
I want to edit the login form provided by django and don't want to build a new one because of the security issues. I have looked at other solutions like How to use another field for logging in with Django Allauth? it's a good example but it assigns email id based on mobile number. However I want to add another field that isn't particularly to authenticate just for input based on which redirection is done. I am quite confused about my approach and whether or not it is possible to do so. Kindly suggest. Thanks. -
ImportError: cannot import name csrf_exemp
I wanna connect my Swift app & Python Django Server in sending Image(I wanna send images from Swift app to Server) When I tried to do it,I got an error <div id="info"> <h2>Help</h2> <p>Reason given for failure:</p> <pre> CSRF cookie not set. </pre> <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when <a href="https://docs.djangoproject.com/en/1.10/ref/csrf/">Django's CSRF mechanism</a> has not been used correctly. For POST forms, you need to ensure:</p> <ul> <li>Your browser is accepting cookies.</li> <li>The view function passes a <code>request</code> to the template's <a href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a> method.</li> <li>In the template, there is a <code>{% csrf_token %}</code> template tag inside each POST form that targets an internal URL.</li> <li>If you are not using <code>CsrfViewMiddleware</code>, then you must use <code>csrf_protect</code> on any views that use the <code>csrf_token</code> template tag, as well as those that accept the POST data.</li> <li>The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.</li> </ul> <p>You're seeing the help section of this page because you have <code>DEBUG = True</code> in your Django … -
python3.6.2 + django1.11.4 + django-mssql1.8 - is this combination supports? Unable to connect sql server from django
I am using pthon3.6.2 + django1.11.4 + django-mssql1.8 combination for my web application and unable to connect to sql server database. Following is the setting I am using in setting.py DATABASES = { 'default': { 'NAME': 'DB1', 'ENGINE': 'sqlserver_ado', 'HOST': '192.168.5.245', 'USER': 'user1', 'PASSWORD': '123456', } } Is this combination supports? i.e. django-mssql1.8 is supported or not with other two. The django-mssql website does not mention this If it supports please advise how to resolve. -
Bootstrap Select Drop Down is not Vertically Listed
I tried to use bootstrap-select to implement a drop down box, but the options are not vertically listed. Did anyone have the same issue before? <script src="{% static 'risk_parity/js/jquery-3.2.1.min.js' %}"></script> <script src="{% static 'risk_parity/js/bootstrap.min.js' %}"></script> <link href="{% static 'risk_parity/css/bootstrap.min.css' %}" rel="stylesheet"> <script type="text/javascript" charset="utf8" src="//code.jquery.com/jquery-1.12.4.js"></script> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css"> <script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script> <select class="selectpicker" > <option>USA</option> <option>CA</option> </select> <script> $(document).ready(function(){ $('.selectpicker').selectpicker(); }); </script> Not Vertically Listed -
Using userena in project and uploading on AWS
I have installed userena. It works fine on the local machine. I want to bring all files of userena into my project so that i can upload my project on AWS. How do i get my project up and running WITH userena on AWS? -
Implement Django oauth to 2 Different User Models
Is there any way to have Django oauth for 2 Different types of User Models? I am working on a site which has Customer and Business, and both will have their seperate logins. There is no such information that they will have in common and really can't use common db table for both. We will be having different database tables for customers and business, thus need different oauth tables. I couldn't find any way to accomplish it. -
Assigning variable value as table column name
if request.POST['table'] == 'a': get_table = A_table() get_column = 'a' elif request.POST['table'] == 'b': get_table = B_table() get_column = 'b' get_table. + get_column + _column = 'some text' The sample code above is just an idea which of course won't work. How do I assign a variable value as table column name in django? this will be used in a separate function for dynamic filtering.. a simpler example would be: tablename.+'col'+name = 'test data' -
Django Contrib Admin 'administration' is not a registered namespace
Awhile back I updated a very large project from Django 1.9 to Django 1.11. Since then I've made a significant amount of changes improving and adding to the project. At some point after the update my Django.contrib.admin site broke and I haven't been able to figure out the cause or the fix. When browsing to my django admin page I receive the following error: Error Trace NoReverseMatch at /admin/ 'administration' is not a registered namespace \env\lib\site-packages\django\contrib\admin\templates\admin\base.html, error at line 3 'administration' is not a registered namespace 1 {% load i18n static %}<!DOCTYPE html> 2 {% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} 3 <html lang="{{ LANGUAGE_CODE|default:"en-us" }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}> First, I thought the proper namespace for django.contrib.admin was 'admin' not 'administration'. Second, I have no idea why line three of the base.html template would cause that error in the first place since it doesn't appear to call any namespaces. My settings appear to be correct to me and in line with the current documentation. Urls.py Excerpt from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.contrib.auth.views import login, logout urlpatterns = [ ... url(r'^login', login, {'template_name': …