Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pycharm doesn't recognize .min.css file (Unresolved template reference) (Django)
I'm using Django with Pycharm. I started to use Pycharm Professional today, and Pycharm doesn't recognize my bootstrap.min.css file. <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}"> Errors I actually have that file in my project folder, but It doesn't appear in Pycharm file tree. my project folder pycharm file tree Of course, I've set the static_dir, staticfiles_dirs, and static_root. django static settings This never happend in Pycharm educational version. -
Javascript variable passed to html textbox but not to Django form
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> function dropfunc(){ var s = document.getElementsByName('parameters')[0]; var text = s.options[s.selectedIndex].text; document.getElementById("mytext").value = text; document.getElementById("distance").value = text; } </script> <form action="/summarize_text/" method="post" enctype="multipart/form-data"> {% csrf_token %} <p><b> Text Summarizer</p></b> <select name = "parameters"> <option>Sentence1</option> <option>Sentence2</option> <option>Sentence3</option> <option>Sentence4</option> </select> <input type = "button" onclick = "dropfunc()" value = "Submit"> <input type="text" id="mytext"> <div class="fieldWrapper"> <label id="distance">Sentence</label> {{form.text_data}} </div> </form> </body> </html> In this code the textbox mytext is responsive to changes in the dropdown but the dropfunc() should make changes in the django form variable distance as well. Please suggest what I am doing wrong. -
Separating Business Workflow from Django Application
I've got a Django App where I need to follow different workflow for different inputs. I receive an input parameter with the data payload over the POST endpoint. Based on the input, I need to fire different functions, process the data accordingly and finally save it in the data store. One option is to write if-else, however writing if-else is difficult in maintaining as the code grows. For eg:- If input1, then function1(), process1(), save1() elif input2, then function2(), process2(), save2() I've looked into Intellect, django-viewflow and many other business-rule libraries, but not sure about the recommended way of doing it. -
Linux Apache Django video static file issue
Ubuntu 16.04, Apache, python 3.6 with django. My view is serving up the path of a static video file to my template. It was working fine running the manage.py dev server. It was not working properly on the apache server. I reloaded apache but still get: "No video with supported format and MIME type found" message in Firefox. Apache didn't have the full path, just a relative path from my django app. So I passed the full path to the template. I get the same error, dev and apache servers. I grabbed the HTML out of the template and it works fine; the video played. www-data has rwx all the way up to the file and the directories. Not sure what is going on. Any help is appreciated. -
Best way to create Slack bot responses using Django REST API
I have a simple piece of code that uses the EventsAPI for Slack, and will recognize certain words or phrases and give the user a response: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.conf import settings from slackclient import SlackClient SLACK_VERIFICATION_TOKEN = getattr(settings, 'SLACK_VERIFICATION_TOKEN', None) SLACK_BOT_USER_TOKEN = getattr(settings, 'SLACK_BOT_USER_TOKEN', None) Client = SlackClient(SLACK_BOT_USER_TOKEN) # Create your views here. class Events(APIView): def post(self, request, *args, **kwargs): slack_message = request.data #verify token if slack_message.get('token') != SLACK_VERIFICATION_TOKEN: return Response(status=status.HTTP_403_FORBIDDEN) #checking for url verification if slack_message.get('type') == 'url_verification': return Response(data=slack_message, status=status.HTTP_200_OK) #send a greeting to the bot if 'event' in slack_message: #process message if event data is contained in it event_message = slack_message.get('event') #ignore bot's own message if event_message.get('subtype') == 'bot_message': return Response(status=status.HTTP_200_OK) #handle the message by parsing the JSON data user = event_message.get('user') text = event_message.get('text') channel = event_message.get('channel') bot_text = 'Hi <@{}> :wave:'.format(user) #finally use the slack api to post the message with chat.postMessage if 'hello' in text.lower(): Client.api_call(method='chat.postMessage', channel=channel, text=bot_text) return Response(status=status.HTTP_200_OK) return Response(status=status.HTTP_200_OK) Obviously I want a much more robust database of keywords. But is the best way to do this … -
Django inspectdb generates TextField for MySQL mediumblob
I have a legacy MySQL database. I decided to generate models from the database tables using 'inspectdb'. I have some images stored as mediumblob fields in a table. I see that Django generated those field as following: origimage = models.TextField(db_column='OrigImage') # Field name made lowercase. Django documentaions says If inspectdb cannot map a column’s type to a model field type, it’ll use TextField and will insert the Python comment 'This field type is a guess.' next to the field in the generated model. I do not see the 'This field type is a guess'. Does not appear like Django treated this as a guess. Does Django translate mediumblob to TextField? I would need to see this as a file upload field in the Forms. Am I to change this to an ImageField for the field to be rendered correctly? -
A better way to order ForeignKey and M2M relations using drag-and-drop libraries like Sortable.js, muuri, etc
As the title says I hacked this together a bit ago as an initial run of handling updating models which are a ForeignKey relation to a base model (creating a related set) that can be ordered by the front-end / user using drag-and-drop libraries. But, this is hackish and can be a lot better I feel. So, the question is: Is there a better / more efficient way using a different schema such as through or method of updating than the below example. Example model layout: class ModelA(models.Model): pass class ModelB(models.Model): order = models.PositiveIntegerField() model_a = models.ForeignKey(ModelA, related_name='items') class Meta: ordering = ['order'] Any time ModelB is added to the items relation set the order is set to be the last. That is, new_instance.order = items.count(). Cool, that let's new items be last as expected. But, on the front-end let's consider drag-and-drop and updating with AJAX requests. Let's say I make a request to a view: update_order with url ^(?P<pk>\d+)/order/(?P<order>\d+)/$ and let's ignore error checking / permissions etcetera. A simplified version of this view is - with pk being a ModelB pk -: Essentially: Partition the set into gte and lt and handle appropriately offsetting lt as [0, order) and … -
Django - Limit the select options of a foreignkey and prevent duplicate objects
I have to create a new object that is related to another models. Model1 (for this model i have to create the new object class ProductStock(models.Model): # Relations product = models.ForeignKey( Product, related_name='product_stock', verbose_name=_('product'), on_delete=CASCADE, ) warehouse = models.ForeignKey( Warehouse, default=1, verbose_name=_('warehouse'), on_delete=CASCADE, ) # Attributes - Mandatory quantity = models.IntegerField( default=0, verbose_name=_('quantity'), ) and I have the Products Model and the Warehouses Model. Well, I have to create an object to define the stock of the product in one of the warehouses, but i only can have 1 object for each product and Warehouse. The problem here is this. For a Product i only can have one object in this model for each warehouse. And if i create 2 items with the same warehouse i have 2 objects with the same product and warehouse and i can't have that result. I can think of 2 ways to prevent it, one (the easy one) is in the model save method check if exist a object with that product and warehouse and raise the error. But I think is better for the User Experience try to limit the select options of warehouses in the form. But i don't know how i … -
How can I convert string to list
I use python djanggo for web development. I got an list from input forms, and I saved the list in my djanggo text fields. Then, I brought it from database and print it. I save the list like that [{'question': 'dsasda', 'type': 'ShortAns',},{'question': 'dsads', 'type': 'MultipleCho','answer': ['asdadsasd',]},] And then, I brought it in view like that survey_list = json.loads(survey.questions) I showed it in template, so {{ survey_list.0 }} But it print out only [ how can I solve this problem -
including bootstrap in django
i am working on a project on django and i want to include bootstrap to it to make it a responsive website.my bootstrap css works perfectly fine each time i include it<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> but when i try to do the same thing for js in bootstrap,it doesn't seem to work,here's my js<script src="https://ajax.gogglepis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> -
How do you add a pre-existing database to psql?
I am using psql in my production server that houses my Django application. I am trying to create a database in psql that already exists. I have the host name, username, password, port, all that good stuff, but after reading psql's documentation it seems that there is no way to add in a prexisting database. -
cryptocurrency payment solution for django-oscar
I have an e-commerce site running on django-oscar (shop.minable.io). I want to integrate cryptocurrency payments. It doesn't seem like anyone has made a plugin for this. Does Coinbase have any plans to release a plugin for this? If I were to make such a plugin myself, how do I go about selling it to Coinbase? -
'tuple' object has no attribute 'Meta'
I'm working with django-rest and I made a filters.py but it marked me the error of suiguitor to be able to add my filters and API and I checked and I have the code correctly it does not mark me any other error more than the rest help me 'tuple' object has no attribute 'Meta' my code in is the following models.py class AutorizarCaptura(models.Model): folio = models.CharField(max_length=12) un = models.CharField(max_length=12) anio = models.IntegerField() fecha_captura = models.DateField(auto_now_add=True, blank=True) def __str__(self): return "%s" % (self.un) def __unicode__(self): return "%s" % (self.un) filters.py class AutorizarCapturaFilter(filters.FilterSet): un = CharFilter( name="un", lookup_expr="exact" ) anio = CharFilter( name="un", lookup_expr="exact" ) class Meta: model=AutorizarCaptura fields = [ 'un', 'anio' ] serialiazers.py class AutorizarCapturaSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = AutorizarCaptura fields = ( 'id', 'folio', 'un', 'anio', 'fecha_captura', ' ) -
How to load .sql file with manage.py
I have a .sql file from one of my production servers, and am now trying to load it into the database of another. I tried python manage.py loaddata, but its giving me an error CommandError: Problem installing fixture 'social': sql is not a known serialization format. How can I load my data into postgres from a .sql file with manage.py ? -
Accessing additional fields for customized UserCreationForm in Django
I am new to Django and working on my first app after running the official tutorial and reading other articles. I am having problem accessing the additional field that I added for User model. I am not able to figure out the problem, any help/pointers will be much appreciated. Forms.py (I have added the field country in the example code shown below) from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit class RegisterUserForm(UserCreationForm): country = forms.CharField() def __init__(self, *args, **kwargs): super(RegisterUserForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-exampleForm' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = '.' self.helper.add_input(Submit('submit', 'Submit')) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super(RegisterUserForm,self).save(commit=False) user.country = self.cleaned_data["country"] print user.country if commit: print "saving user" user.save() return user Views.py from django.shortcuts import render from django.views.generic import CreateView from .forms import RegisterUserForm class RegisterUserView(CreateView): form_class = RegisterUserForm template_name = 'accounts/register.html' success_url = '/' Admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from .forms import RegisterUserForm class NewUserAdmin(UserAdmin): add_form = RegisterUserForm admin.site.unregister(User) admin.site.register(User, NewUserAdmin) PROBLEM : In the admin app, … -
How to prevent DRF from escaping my non-ascii characters (UNICODE_JSON is True)
I've tried out a few versions of DRF that are compatible with Django 2.0, and they're escaping my non-ascii characters in my JSON. Here's an example JsonResponse: ["C\u00e2\u0080\u0099est int\u00c3\u00a9ressant ... I'm presently running 3.7.7. As per the encoding docs, I have set: UNICODE_JSON: True (though this is the default anyway) I'm still getting escaped chars, contrary to what the docs indicate. The other parts of my pages (handled by Django) render their accented characters fine, and my postgres client_encoding is 'UTF8'; it's definitely a DRF issue. How can I fix this? -
How do I deploy a Django server running in a docker on Digital Ocean Ngnix
I have never set up a server on digital ocean before and I am trying to set up my django website that runs inside a docker container and have it run on a django ubuntu digital ocean server. Can someone just list me through some basic steps of what needs to be done, I don't know how to have tell the digital ocean server to run my docker container and run the following command: "docker-compose -f dev.yml up". I read that you need to configure the Ngnix document, but i'm still confused. I watched this video: https://youtu.be/Y-CT_l1dnVU. I just cant wrap my head around the big picture I guess of what Ngnix and Gunicorn do and how the docker container is suppose to run on digital ocean. Any help is appreciated! Thanks -
Django Rest API isn't responding with the value of the challenge parameter
Working my way through this tutorial and it has been going mostly well until I try to verify my app with the slack API by submitting a ngrok tunnel link, which is <myID>.nrgok.io/events. I keep receiving 500 error: Your URL didn't respond with the value of the challenge parameter. Why isn't my app responding with the challenge parameter? # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.conf import settings from slackclient import SlackClient SLACK_VERIFICATION_TOKEN = getattr(settings, 'SLACK_VERIFICATION_TOKEN', None) SLACK_BOT_USER_TOKEN = getattr(settings, 'SLACK_BOT_USER_TOKEN', None) Client = SlackClient(SLACK_BOT_USER_TOKEN) # Create your views here. class Events(APIView): def post(self, request, *args, **kwargs): slack_message = request.data #verify token if slack_message.get('token') != SLACK_VERIFICATION_TOKEN: return Response(status=status.HTTP_403_FORBIDDEN) #checking for url verification if slack_message.get('type') == 'url_verification': return Response(data=slack_message, status=status.HTTP_200_OK) #send a greeting to the bot if 'event' in slack_message: #process message if event data is contained in it event_message = slack_message.get('event') #ignore bot's own message if event_message.get('subtype') == 'bot_message': return Response(status=status.HTTP_200_OK) #handle the message by parsing the JSON data user = event_message.get('user') text = event_message.get('text') channel = event_message.get('channel') bot_text = 'Hi <@{}> :wave:'.format(user) #finally use the slack api to post the … -
Django AWS RDS settings - EB deployment
I have a Django application on AWS Elastic Beanstalk. I am trying to connect my application to an external RDS database (mySQL). I have followed this tutorial to get this kind of setting: if 'RDS_DB_NAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myName', 'USER': 'myUser', 'PASSWORD': 'myPassword', 'HOST': 'localhost', 'PORT': '5432', } } Everything works fine on AWS but when I redeploy my application I lose all the data in my database, e.g. all of the users's sign-ups are gone. That means the deployment overwrite the previous database and my application is not connected to an external RDS where data should be preserved. Any idea about what I am doing wrong? Thank you very much for your help ! Regards -
Constraint Issue When Loading .sql file into Postgres DB
I performed a pg_dump on the entirety of my production database, and tried to upload it locally on a newly migrated clean Postgres DB. When I do psal db_name < data.sql, I get errors like this insert or update on table "vehicle_vehicle" violates foreign key constraint "vehicle_vehi_vehicle_make_id_265a8146_fk_vehicle_vehiclemake_id" DETAIL: Key (vehicle_make_id)=(788) is not present in table "vehicle_vehiclemake". When a table with foreign keys is attempted to be loaded, and another table it has foreign key relationships to hasn't been uploaded yet, does Postgres stop what its doing and starts to load that table ? How does loading data tackle this issue, is it one the user to dump the data table by table, and load them one at a time ? -
Django DisallowedHost at /, adding it causes connection to be refused
I'm facing a Django DisallowedHost error, googling the solution lead me to add the domains in question to the ALLOWED_HOSTS list in settings.py. However, doing so causes the connection to flat out refuse to connect, and seemingly force https. DisallowedHost Error log: https://pastebin.com/sEg73qmV django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'www.davixxa.net'. You may need to add 'www.davixxa.net' to ALLOWED_HOSTS. This being the specific error of interest. Any help would be greatly appreciated -
validate and submit Django form (django-crispy-forms) with Ajax
I'm very new at django and web development. I need help submitting Django form (using django-crispy-forms) with Ajax How do I: 1 validate input 2 submit without reloading 3 display errors in case of validation failure Right now i can submit the form and it saves the entries into the database but reloads the entire page in the process. i have included relevant snippets of my code below // forms.py class SubscriptionForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(SubscriptionForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.template_pack = 'bootstrap3' self.helper.form_tag = True self.helper.form_id = 'sub-form-1' self.helper.form_class = 'form-inline' self.helper.field_template = 'bootstrap3/inline_field.html' self.helper.layout = Layout( Div(Div(css_class='sub-form-notifications-content'), css_class='sub-form-notifications'), InlineField('name', id='subName'), InlineField('email', id='subEmail'), FormActions(Submit('submit', 'Notify me', css_class='form-control')), ) class Meta: model = Sub fields = "__all__" def clean_email(self): """ Validate that the supplied email address is unique for the site. """ if User.objects.filter(email__iexact=self.cleaned_data['email']): raise forms.ValidationError( _("This email address is already in use. Please supply a different email address.")) return self.cleaned_data['email'] // views.py from django.shortcuts import render, redirect from .forms import SubscriptionForm from .models import Sub def index(request): if request.method == 'POST': sub_form = SubscriptionForm(request.POST) if sub_form.is_valid(): sub_form.save() # return redirect('landing:landing') else: sub_form = SubscriptionForm() return render(request, 'landing/index.html', {'sub-form': sub_form}) // template ... {% crispy sub-form %} ... -
Django Rest Framework - How to route to a function view
I am using Django with Django Rest Framework. Django==2.0.2 djangorestframework==3.7.7 I am trying to route to a function view. My current setup looks like this: - project - project - urls - app - urls - views In project/urls, I reference the app's urls like this: url(r'^app_api/', include('app_api.urls', namespace='app_api')) In app/urls, I route to the views like this: router.register(r'', views.app_api, base_name="app_api") url(r'', include(router.urls)), In app/views I have defined a function called app_api and decorated it with api_view. @api_view(['GET']) def app_api(request): If I run the server and curl http://localhost:8080/app_api/ for example, I get a response with status 200 and a empty JSON. "GET /app_api/ HTTP/1.1" 200 2 {} I do not understand why this is happening. If I use a class based viewset, it works, but not with a function view. What is the correct way of routing to a function view when using Django Rest Framework? Thanks! -
How to expand existing input formats in forms.datetime field?
I'd like to add custom input format for my DateTimeField. Is it possible to add custom input without hardcoding default inputs? class CustomForm(forms.Form): updated = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%fZ']) I want to add the option that is above and this solution don't look good: class CustomForm(forms.Form): updated = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%fZ', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M', '%m/%d/%y']) -
Running WhiteNoise locally for Django development
I'm trying to serve static files on a Django project with DEBUG = False. I found the WhiteNoise project and configured it according to the docs, and my project works great when deployed to Amazon Web Services. However, when I try to run the project locally, the static files aren't served. I've tried running python3 manage.py runserver --nostatic and also adding 'whitenoise.runserver_nostatic' in INSTALLED_APPS per the docs here. The static files still aren't being served locally, though. Does anyone know if there are some other settings or configurations I should be changing?